jQuery press button as enter on a text field

10,454

Solution 1

define what should happen on keypress event for #address. Look at this code. Press enter key from insde the text box and then click on the button, both trigger the keypress event.

demo - http://jsbin.com/ocohev/1/edit

    $(function () {

        $('#address').keypress(function (event) {
            if (event.which == 13) {
                alert("enter pressed");
                //return false; only if needed
            }
        });

        $("#ricerca").click(function () {
            var e = jQuery.Event('keypress');
            e.which = 13; // #13 = Enter key
            $("#address").focus();
            $("#address").trigger(e);
        });

    });

Solution 2

Use this Jquery code:

$("#id_of_textbox").keyup(function(event){
    if(event.keyCode == 13){
        $("#id_of_button").click();
    }
});
Share:
10,454
Perocat
Author by

Perocat

Updated on June 04, 2022

Comments

  • Perocat
    Perocat almost 2 years

    I have this text field:

    <input id="address" type="text" value="">
    

    and this button:

    <input id="ricerca" type="button" class="enter" value="GO!">
    

    and jQuery:

    $("#ricerca").click(function(){
        var e = jQuery.Event('keypress');
        e.which = 13; // #13 = Enter key
        $("#address").focus();
        $("#address").trigger(e);
    });
    

    I want to simulate the "Enter" press INSIDE the #address field, by clicking on the #ricerca button. It is necessary that the cursor is inside the #address field when I press the button.

    Can you please say me where are the errors?