Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery button submit with enter key function

Tags:

jquery

I have a button submit like this :

<input type="button" id="button_sign_in" class="button_sign_in" value="Sign in"/>

and I have jQuery submit like this :

$(document).ready(function()
    {
        $('#button_sign_in').click(function(){
             console.log('login');
            $.ajax
            ({
                url: "login",
                type: "post",
                data: $('#login_form').serialize(),
                dataType:'json',
                success: function (data) 
                {
                    if (data.status=='SUCCESS') 
                    {
                        window.location='home.php'; 
                    }
                    else 
                    {
                        $('#button_sign_in').shake(4,6,700,'#CC2222');
                        $('#username').focus();
                    }
                },
                error: function (e) {
                    console.log('error:'+e);
                }
            });
        });
    });

The problem is : we can't submit using enter key, so user must click the button Sign in to submit.

What I want ? set enter key into JS function, so user can choose submit using enter key or click the button Sign in.

Thanks for any help.

like image 462
HiDayurie Dave Avatar asked Dec 08 '22 14:12

HiDayurie Dave


1 Answers

Check this demo http://jsfiddle.net/yeyene/hd7zqafg/

First click on the result frame (because there are another frames), and press enter, the submit button click event will fire on Enter key press & on button click.

$(document).ready(function()               
    {
        // enter keyd
        $(document).bind('keypress', function(e) {
            if(e.keyCode==13){
                 $('#button_sign_in').trigger('click');
             }
        });

        $('#button_sign_in').click(function(){
            alert('You click submit!');
             console.log('login');
            $.ajax
            ({
                url: "login",
                type: "post",
                data: $('#login_form').serialize(),
                dataType:'json',
                success: function (data) 
                {
                    if (data.status=='SUCCESS') 
                    {
                        window.location='home.php'; 
                    }
                    else 
                    {
                        $('#button_sign_in').shake(4,6,700,'#CC2222');
                        $('#username').focus();
                    }
                },
                error: function (e) {
                    console.log('error:'+e);
                }
            });
        });
    });
like image 195
yeyene Avatar answered Dec 23 '22 23:12

yeyene