JQuery, bind the same function to 3 different keyword input events

I have 3 text fields, and in the keyup event for all 3, I want to call the same function?

In the code below, I am tring to associate a keyup event with a CalculateTotalOnKeyUpEvent function with a text field called compensation , but it does not work:

 $("#compensation").bind("keyup", CalculateTotalOnKeyUpEvent(keyupEvent)); function CalculateTotalOnKeyUpEvent(keyupEvent) { var keyCode = keyupEvent.keyCode; if (KeyStrokeAllowdToCalculateRefund(keyCode)) { CalculateTotalRefund(); } }; 
+6
javascript jquery events bind
source share
5 answers

You need to do this:

 // Edit according to request in the comment: // in order to select more than one element, // you need to specify comma separated ids. // Also, maybe you need to consider to use a CSS class for the selected elements, // then it could be just $(".className") $("#element1, #element2, ....").bind("keyup", CalculateTotalOnKeyUpEvent); 

You need to pass the function as a parameter, you do not need to pass the function as announced.

+12
source share
 $("#txt1, #txt2, #txt3").keyup(fn); 
+5
source share

or just give all 3 text fields the same class and you are good to go

+2
source share

You call CalculateTotalOnKeyUpEvent immediately without passing it as an argument. Try the following:

 $("#compensation").bind("keyup",CalculateTotalOnKeyUpEvent); 
0
source share
 $("#compensation").bind("keyup",CalculateTotalOnKeyUpEvent(keyupEvent)); 

When you write CalculateTotalOnKeyUpEvent (keyUpEvent) [note the function name after the function name], you execute CalculateTotalOnKeyUpEvent and assign the result of the function to the key event.

You should do something like

 $('#compensation, #otherId1, #otherId2') .bind('keyup', CalculateTotalOnKeyUpEvent); 

Where 'otherId1' and 'otherId2' are the identifiers of two more text fields.

0
source share

All Articles