rnldpbln
rnldpbln

Reputation: 674

Run function on enter press

I have a jQuery button function that works properly and executes the code inside, what I want is when I press the Enter on the search box, it will execute the same function inside the onclick one. I don't want to copy paste the entire code of my function to the on Enter press event because that will be the wrong way to do it. This is the click event:

$("#checkScout").click(function(e){
 ...
}

And this is the one I tried with the on enter press

var enterKey = document.getElementById("addChannelsToScout");
enterKey.addEventListener("keydown", function (e) {
    if (e.keyCode === 13) {
        $("#checkScout").click(function (e);
    }
});

Upvotes: 0

Views: 113

Answers (5)

Milind Anantwar
Milind Anantwar

Reputation: 82231

Try:

$("#checkScout").trigger('click');

Trigger Performance

Upvotes: 1

zzlalani
zzlalani

Reputation: 24354

actually you need to trigger the event. since it is already been handled it will perform the task that you have written in the event

Check Triggers here http://api.jquery.com/trigger/

$("#checkScout").trigger("click");

Upvotes: 0

just this will work $("#checkScout").click();

var enterKey = document.getElementById("addChannelsToScout");
    enterKey.addEventListener("keydown", function (e) {
        if (e.keyCode === 13) 
        {  
          $("#checkScout").click();
        }
    });

Upvotes: 0

Somnath Kharat
Somnath Kharat

Reputation: 3600

Change:

 $("#checkScout").click(function(e);

To:

  $("#checkScout").click();

Your code:

var enterKey = document.getElementById("addChannelsToScout");
    enterKey.addEventListener("keydown", function (e) {
        if (e.keyCode === 13) 
        {  
          $("#checkScout").click();//modified here
        }
    });

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

it should be just

$("#checkScout").click();

so

$('#addChannelsToScout').keydown(function (e) {
    if (e.which == 13) {
        $("#checkScout").click();
        //$("#checkScout").trigger('click');
    }
})

Demo: Fiddle

Upvotes: 2

Related Questions