3zzy 3zzy - 7 months ago 31
jQuery Question

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/

Answer

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.