Monday 1 July 2019

jQuery multiple events to trigger the same function



Is there a way to have keyup, keypress, blur, and change events call the same function in one line or do I have to do them separately?




The problem I have is that I need to validate some data with a db lookup and would like to make sure validation is not missed in any case, whether it is typed or pasted into the box.


Answer



You can use .on() to bind a function to multiple events:



$('#element').on('keyup keypress blur change', function(e) {
// e.type is the type of event fired
});



Or just pass the function as the parameter to normal event functions:



var myFunction = function() {
...
}

$('#element')
.keyup(myFunction)
.keypress(myFunction)
.blur(myFunction)

.change(myFunction)

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...