yltang52 yltang52 - 5 months ago 14
Javascript Question

jquery input on change: zero and empty

I am using jQuery's

.on('change')
event to detect if the value of an input field has been changed. However, for an initially empty input field, if the user enters 0, the input field will be cleared and the value is considered not changed, as follows:

HTML:

<input id=number type=text>


jQuery:

var $number = $('#number');
$number.on('blur', function() {
if (this.value == 0) {
this.value = '';
}
});

$number.on('change', function() {
console.log('Changed.');
});


The event
change
is always triggered when the user enters zero. How do I prevent it from happening?

Answer

i think this is what you want

var number = $('#number');

number.on('change', function() {
    if ($(this).val() == 0) 
    {
        $(this).val('');
        return false;
    }
   else
    {
       //do Your stuff here 
     }

  ); 

 var number = $('#number');

    number.on('change', function() {
       
      if ($(this).val() == 0) 
        {
            $(this).val('');
            return false;
        }
       else
        {
          alert("value enter 0");
           //do Your stuff here 
         }
    }); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id=number type=text>

Comments