March 3, 2013

How can I combine 2 or more jquery keydown functions into one function?

Question by Pachonk

My goal:

To clean up multiple keydown functions leading to the same button press by making it one function.

My issue:

I have made many functions like this:

$("#username").keydown(function(event){
    if(event.keyCode == 13) {
        $('#loginbtn').click();
    };
});
$("#password").keydown(function(event){
    if(event.keyCode == 13) {
        $('#loginbtn').click();
    };
});

That trigger button clicks on buttons. It is too messy and uses many lines. I want to combine the lines into one function. I have many boxes for my registration form as well.

What have I tried?

1.
I have tried the following code bellow and other replications which do not work:

$("#username","#password").keydown(function(event){
    if(event.keyCode == 13) {
        $('#loginbtn').click();
    };
});

2.
Another idea I had was to use a class, I just don’t know if this is considered the “proper” way to do it, so I need opinions:

$(".logintextbox").keydown(function(event){
    if(event.keyCode == 13) {
        $('#loginbtn').click();
    };
});

Then I would also add that class in my html so all of the login text boxes and all of the register text boxes have unique classes “grouping” them.

My question/tl;dr:

How can I combine 2 or more jquery keydown functions into one function using multiple id’s or one class?

Answer by Starx

I suggest delegating from your form instead of individual elements.

$("#your_form_id").on('keydown', 'input', function(event){
    if(event.keyCode == 13) {
        $('#loginbtn').click();
    };
});

This will capture the key being pressed on all inputs within your form.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!