clear textbox not work

I'm trying to showing clear textbox if only we typing the text why it didnt show the clear text when I type something on textbox

Is there any suggestion how to fix it

$(document).ready(function(){
  if($('.txt-input').val().length === 0){
    $('.erase').hide();
  }
  else{
     $('.erase').show();
  };
  
  $(".erase").click(function(){
    $('.txt-input').val('');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input type="text" class="txt-input"/>
</form>
<p class="erase">clear</p>

Answers 1

  • You need to create a listener to listen the changes of the input field.

    $(document).ready(function(){ 
      $('.txt-input').on('keyup', function(){
        if($(this).val().length === 0 ){
             $('.erase').hide();
        }else{
             $('.erase').show();
        }
      });
    
      $(".erase").click(function(){
        $('.txt-input').val('');
      });
    });
    

Related Articles