admin管理员组

文章数量:1201569

I have 3 textboxes, and on the keyup event for all 3, I want to call the same function?

In the below code, I am tring to bind keyup event to CalculateTotalOnKeyUpEvent function to a textbox named compensation, but it doesn't work:

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

function CalculateTotalOnKeyUpEvent(keyupEvent) {
  var keyCode = keyupEvent.keyCode;
  if (KeyStrokeAllowdToCalculateRefund(keyCode)) {
    CalculateTotalRefund();
  }
};

I have 3 textboxes, and on the keyup event for all 3, I want to call the same function?

In the below code, I am tring to bind keyup event to CalculateTotalOnKeyUpEvent function to a textbox named compensation, but it doesn't work:

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

function CalculateTotalOnKeyUpEvent(keyupEvent) {
  var keyCode = keyupEvent.keyCode;
  if (KeyStrokeAllowdToCalculateRefund(keyCode)) {
    CalculateTotalRefund();
  }
};
Share Improve this question edited Aug 15, 2013 at 15:41 user456814 asked Jul 16, 2009 at 14:32 MiralMiral 6,03817 gold badges59 silver badges86 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 12

You need do like 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 it was declared.

$("#txt1, #txt2, #txt3").keyup(fn);

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

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

When you write CalculateTotalOnKeyUpEvent(keyUpEvent) [notice the () after function name], you are executing the CalculateTotalOnKeyUpEvent and assigning the result of the function to the key up event.

You should do something like,

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

Where 'otherId1' and 'otherId2' are the ids of two more textboxes.

You are calling CalculateTotalOnKeyUpEvent immediately, not passing it as an argument. Try this:

$("#compensation").bind("keyup",CalculateTotalOnKeyUpEvent);

本文标签: JavaScriptJQuerybind same function to 3 different textboxs39 keyup eventStack Overflow