tonyf
tonyf

Reputation: 35539

How to Combine Two Different Trigger Events using jQuery

I have the following events that can occur on two different fields but on the subject field, apart from also triggering a change event, I would also like to catch if the user presses the enter key instead of the tab key, i.e.:

$("#P300_FILE_NAME,#P300_SUBJECT").change(function(){
   ... do some processing ....
});

Now from another thread here in SO, I found the following code snippet from here, i.e.

$("#P300_SUBJECT").enterKey(function () {

that works a treat when the enter key is pressed but I would like to incorporate it as part of the above change event code processing, where it can either check if the user pressed the tab key on the subject field or pressed the enter key instead.

Unsure how I can combine the two events in order to perform the necessary "...do some processing ..." code.

It's almost like I need something like:

$("#P300_FILE_NAME,#P300_SUBJECT").change(function() || $("#P300_SUBJECT").enterKey(function () {

Upvotes: 0

Views: 192

Answers (2)

Jashwant
Jashwant

Reputation: 28995

var foo = function () {
  // Put your code here.
}


$("#P300_FILE_NAME,#P300_SUBJECT").change(foo);
$("#P300_SUBJECT").enterKey(foo);

Upvotes: 1

nbrooks
nbrooks

Reputation: 18233

You can use on to bind an event handler which is triggered on multiple different events. In this case, you want to trigger the event on change and on keypress. I don't think there's an enterKey event, so I'm not sure where that came from, as it doesn't appear to be a jQuery method either.

$("#P300_FILE_NAME, #P300_SUBJECT").on("change keypress", function (e) {
    if (e.type == "keypress" && 
       ($(this).is("#P300_FILE_NAME") || e.which != 13) {
        return false;
    }
    ....
});

Upvotes: 0

Related Questions