eozzy
eozzy

Reputation: 68780

Input value change not detected

var input = $('input[type="number"]', this);
$('.inc').on('click', function(){
  input.val( parseFloat(input.val()) + parseFloat(0.5));
});

... increments the value of the input correctly. However, I can't get change event with:

$('input[type="number"]').on('propertychange change keyup input paste', function(){
  console.log('change'); 
});

What am I doing wrong here?

https://jsfiddle.net/cf5vhb2c/

Upvotes: 1

Views: 1729

Answers (2)

eisbehr
eisbehr

Reputation: 12452

You need to trigger change too, because a programatically set of the value will not trigger any event by default.

var input = $('input[type="number"]', this);
$('.inc').on('click', function(){
    input.val(parseFloat(input.val()) + parseFloat(0.5)).trigger("change");
});

Beside this you need to declare your updateTotal function befor using it in the event listener creation.

var updateTotal = function() {
    console.log('change');
}
$('.hours input[type="number"]').on('change', updateTotal);

Or declare a named function:

$('.hours input[type="number"]').on('change', updateTotal);
function updateTotal() {
    console.log('change');
}

Or use a anonymous function directly:

$('.hours input[type="number"]').on('change', function() {
    console.log('change');
});

Working example.

Upvotes: 3

Jos
Jos

Reputation: 62

You can always call a function after changing the value:

var input = $('input[type="number"]', this);
$('.inc').on('click', function(){
  input.val( parseFloat(input.val()) + parseFloat(0.5));
  do_something();
});

function do_something() {
   console.log('change'); 
}

Ofcourse you have to change this code too, to execute all in one function:

$('input[type="number"]').on('propertychange change keyup input paste', function(){
  do_something();
});

Another thing that comes in my mind is the following, didn't test it though:

$('.inc').on('click', function(){
  input.val( parseFloat(input.val()) + parseFloat(0.5)).trigger('change');
});

Upvotes: -1

Related Questions