Reputation: 12563
I am wondering if there is an easy way to check that there is been a keyUp event which caused change? I know that it is possible to bind both events:
$("#my-element").bind("change keyup", function(e) {
// code
})
The code above will be triggered when either keyup or change events was triggered, but is there an elegant way to say "keyup event which caused a change"?
Upvotes: 1
Views: 1296
Reputation: 3
I would like to suggest you to use input event if the element is input type.
$("input[name='inputname']").on("input", function () {
console.log($(this).val());
});
Otherwise, you could approach by binding "keyup" event and try to determine whether the pressed key changes the filed value or not.
$("input[name='inputname']").on("keyup", function (e) {
if ($.inArray(e.keyCode, [8, 9, 13, 27, 46, 110, 190]) !== -1
|| (e.keyCode >= 35 && e.keyCode <= 39)) {
return;
} else {
console.log(e.keyCode);
}
/* you might want to use prevnetDefault() for prevent default action when the evnet triggerd.
* (e.g. Below code ensures that it's a alphabet key.)
*/
if ((e.keyCode < 65 || e.keyCode > 90) && (e.keyCode < 97 || e.keyCode > 122)) {
e.preventDefault();
}
});
Upvotes: 0
Reputation: 1750
$("#my-element").bind("keyup", function(e) {
var val = $(this).val();
//if value change
if( $(this).data('last') != val ){
}
$(this).data('last',val);
})
Upvotes: 3
Reputation: 5747
The most simple way to my mind would be to store the current value of the element in memory and check whether that value is different in the keyup callback. var oldValue = $('#my-element').val()
$("#my-element").bind("keyup", function(e) {
if($('#my-element').val() !== oldValue) {
// do something
oldValue = $('#my-element').val();
}
})
Upvotes: 1