Evgenij Reznik
Evgenij Reznik

Reputation: 18594

Combine 2 events when document loads

How can I bind 2 different events when the document loads?

I have a text field and a button. The function should be executed either when the button is clicked:

$(document).ready(function() {
    $("button").click(function() {
       myFunction();
    });
});

or when Enter is pressed:

$("#id_of_textbox").keyup(function(event){
    if(event.keyCode == 13){
        myFunction();
    }
});

But how to combine both events?

Upvotes: 0

Views: 43

Answers (2)

Max
Max

Reputation: 701

Did you want this:

$(document).ready(function() {
    $("button").click(function() {
       myFunction();
    });
    $("#id_of_textbox").keyup(function(event){
        if(event.keyCode == 13){
            myFunction();
        }
    });
});

Upvotes: 1

WhiteHat
WhiteHat

Reputation: 61222

You can bind your function to as many events as needed, here's one way...

$(document).ready(function() {
    $("button").click(myFunction);
    $("#id_of_textbox").keyup(myFunction);
});


function myFunction(event) {
  if ((event.type === 'keyup') && (event.keyCode !== 13)) {
    return;
  }
  // process event here
}

Upvotes: 0

Related Questions