I use the following lines to trigger events when an input value changes which works as intended. However, this also fires when I just click in the input field (without doing or changing anything there).
Is there a way that I can either prevent that it just fires on a click in the input field OR that it only fires when the value changes ? I am looking for a solution that works both on input and paste.
My jQuery:
$('input[type="text"]').bind('keyup mouseup', function() {
var val = $(this).val();
var isnum = /\d/.test(val);
if(isnum == true) {
// do some stuff;
} else {
// do some other stuff;
}
});
Many thanks in advance for any help with this, Tom
You can simply bind input
and paste
events on the element like:
$('input[type="text"]').on('input paste', function() {
var val = $(this).val();
var isnum = /\d/.test(val);
if(isnum == true) {
// do some stuff;
} else {
// do some other stuff;
}
});
Please note that the input
event is fired every time the value of the element changes. This is unlike the change
event, which only fires when the value is committed, such as by pressing the enter key, selecting a value from a list of options, and the like.
Also, you can use .on()
method instead of .bind()
as the .on()
method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on()
method provides all functionality required for attaching event handlers.