Close button for clearing the text

I have a form with textbox and a button as follows:

   <input name="search" type="text" />
   <button class="close" id="markclick" style="position:absolute"></button>

<script>
$('#markclick').click(function()
{

 $('.name').val('');
}
</script>

when I click on button, it is clearing the textbox but one thing is , how do I enable the button only on typing a text in textbox? Any input on this?

Answers 1

  • Use .toggle to play with the display property of the element And input event to handle change in the input value.

    .toggle(Boolean) Display or hide the matched elements.


    The DOM input event is fired synchronously when the value of an <input> or <textarea> element is changed.[Ref]

    Note: button should be display:none initially. or use .trigger('input') to invoke input handler.

    $('[name="search"]').on('input', function() {
      $('#markclick').toggle(!!this.value); //return true if value!=''
    });
    $('#markclick').on('click', function() {
      $('[name="search"]').val('');
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <input name="search" type="text" />
    <br>
    <button class="close" id="markclick" style="position:absolute;display:none">Clear</button>


Related Articles