HiDayurie Dave
HiDayurie Dave

Reputation: 1807

jQuery button submit with enter key function

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.

Upvotes: 5

Views: 27363

Answers (7)

Rana Bhopale
Rana Bhopale

Reputation: 51

 // Get the input field
var input = document.getElementById("myInput");

// Execute a function when the user releases a key on the keyboard
input.addEventListener("keyup", function(event) {
  // Cancel the default action, if needed
  event.preventDefault();
  // Number 13 is the "Enter" key on the keyboard
  if (event.keyCode === 13) {
    // Trigger the button element with a click
    document.getElementById("myBtn").click();
  }
});

Upvotes: 0

yeyene
yeyene

Reputation: 7380

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);
                }
            });
        });
    });

Upvotes: 13

Brett Caswell
Brett Caswell

Reputation: 1504

You need to attach an event to the proper element (probably an input), which I assume is a 'username' (textbox) input or (more likely) the 'password' (password) input.

jsFiddle: http://jsfiddle.net/tyxPu/

jQuery Section

$(document).ready(function () {
    var xhrJSON;
    $('#button_sign_in').click(function () {
        console.log('login');
        xhrJSON = $.ajax({
            url: "about:blank",
            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();
                    $("#debugger").append("<p>Button Click - Failed to 'Sign In'</p>")
                }
            },
            error: function (e) {
                console.log('error:' + e);
                $("#debugger").append("<p>Error - Button Click - Failed to 'Sign In'</p>")
            }
        });
    });
    $("#username").keypress(function (event) {
        if (event.which == 13) {
            xhrJSON = $.ajax({
                url: "about:blank",
                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();
                        $("#debugger").append("<p>Button Click - Failed to 'Sign In'</p>");
                    }
                },
                error: function (e) {
                    $("#debugger").append("<p>Error - Keypress - Failed to 'Sign In'</p>");
                }
            });
        }
    });
});

HTML Section

<form id="login_form">
    <input type="textbox" id="username" placeholder="User Name" />
    <input type="button" id="button_sign_in" value="Sign In" />
</form>
<div id="debugger"></div>

Upvotes: 0

Nick C.
Nick C.

Reputation: 191

Extract the call to $.ajax to a new function called something like submitForm.

Then bind that function to all the elements that can cause a submission:

function submitForm() {
    $.ajax... etc.
}

$('#button_sign_in').on('click', submitForm);
$('#your_input_textbox').on('keypress', function(e) {
    if (e.keyCode === 13) {
        submitForm();
    }
});

Upvotes: 2

Aldi Unanto
Aldi Unanto

Reputation: 3682

If you only use jQuery.Ajax, certainly not be able to submission when you press enter. You have to add <form></form> tag to realize it, and change the JS.

$('form').submit(function(){ //do ajax here })

Upvotes: 0

jsonx
jsonx

Reputation: 1090

Change your input type as submit and prevent default of your submit button. Also your submit button should be wrapped by a form.

$("form").on("submit", function() { return false; });

Upvotes: 0

hzoo
hzoo

Reputation: 1374

wrap the input in a form. If you press enter in the text box it will submit the form.

HTML

<form>
    <input type="text"/>
    <input type="submit" id="button_sign_in" class="button_sign_in" value="Sign in"/>
</form>

change the input type to "submit" and call .submit() instead of .click() on the form.

JS

$('form').submit(function(){
    console.log('login');
});

http://jsfiddle.net/nQ5fN/

Upvotes: 1

Related Questions