Loolooii
Loolooii

Reputation: 9170

Why doesn't this custom submit work?

I have this button which submits the login form:

<input class="btn btn-large btn-success" id="login-button" onclick="handleLogin()" name="submit" type="submit" value="Login"/>

And I have this function which I want to use to have a custom submit when the user presses enter:

$(document).ready(function () {

     $(document).keyup(function(event) { 

        if(event.which == 13) {

            $('#login-button').click();
            //event.preventDefault();
            //return false;
        }
    });
});

However this doesn't do anything at all. I have tried with and without the commented part of the code. Note that the submission of the form works when clicking and that I don't have my input fields inside form element. I am using handleLogin() to submit using AJAX. So all I really want is this #login-button to get clicked! Do you guys see the problem? Thanks in advance.

UPDATE: I'm using Chrome BETA channel.

IMPORTANT!: I want #login-button to get clicked when pressing ENTER. Nothing more that that. I already know how to submit a form.

Upvotes: 2

Views: 174

Answers (2)

Roko C. Buljan
Roko C. Buljan

Reputation: 206171

demo fiddle

$(document).ready(function () {    
     $(document).keyup(function(event) {  
        if(event.keyCode === 13) {

            $('#yourForm').submit(); // submit form
             alert('yeah!')
          
            event.preventDefault();
            return false;
        }          
     });     
});

use: keyCode instead of which
use: .submit() with the name or id of your form. http://api.jquery.com/submit/
You were missing a });

Upvotes: 4

luchopintado
luchopintado

Reputation: 939

here a better way to handle submit form events:

<form id="form">
...
//input texts ...
...
<input type="submit" value="Send"/>
</form>

then, the jquery (you don't need know the pressed key, only the submit event dispatched by the submit button or the enter key):

$("#form").submit(function(e){
e.preventDefault();
//your logic ...
});

Upvotes: 1

Related Questions