How to create a custom event in jquery
-
06-12-2019 - |
質問
I want to create a custom event that will be triggered whenever a numeric value is entered in an input type="text"
. Alphabets should be ignored. change
and blur
events didn't work well for me.
Any suggestions? Thanks.
解決
You might still be able to use change
or blur
events, but insert some additional logic to detect if your input is something that you'd want to trigger an event with, so
$(".field").on("change blur keydown keyup", function(){
if($(this).val().match(/^\d+$/){
//your code
} else {
//do nothing
}
});
他のヒント
You can easily create custom events :
// handle event
$('#mydiv').on('customevent', function(e) { });
// trigger event
$('#mydiv').trigger('customevent');
You're looking for a keydown
, keypress
or keyup
event to catch input, and reject non-numeric input.
Out of these three options, for integer input, the keypress
event very suitable.
$('input#selector').keypress(function(event) {
if (e.which < 48 || e.which > 57) { // or:
//if (!/\d/.test(String.fromCharCode(e.which))) {
event.preventDefault();
}
});
However, you should also use blur
/ change
, to deal with input from copy-pasting/dragging.
$( '#input-id' ).keyup(function(e)
{
if (e.keyCode >= 48 && e.keyCode <= 57 )
{
doThis();
}
});
I think this will help you..
good artical is here..http://javascript.mfields.org/2011/creating-custom-events-with-jquery/ but i cant think it needs .you can use keydown, keypress or keyup as suggested by Rob.