javascript tutorial - [Solved-5 Solutions] Trigger a button click with JavaScript on the Enter key in a text box - javascript - java script - javascript array



Problem:

How to trigger a button click with JavaScript on the Enter key in a text box ?

Solution 1:

only want the Enter key to click this specific button if it is pressed from within this one text box

<input type="text" id="txtSearch" />
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />
click below button to copy the code. By JavaScript tutorial team

Solution 2:

In jQuery, the following would work:

$("#id_of_textbox").keyup(function(event){
    if(event.keyCode == 13){
        $("#id_of_button").click();
    }
});
click below button to copy the code. By JavaScript tutorial team

Or in plain JavaScript, the following would work:

document.getElementById("id_of_textbox")
    .addEventListener("keyup", function(event) {
    event.preventDefault();
    if (event.keyCode == 13) {
        document.getElementById("id_of_button").click();
    }
});
click below button to copy the code. By JavaScript tutorial team

Solution 3:

code it in!

<input type = "text"
       id = "txtSearch" 
       onkeydown = "if (event.keyCode == 13)
                        document.getElementById('btnSearch').click()"    
/>

<input type = "button"
       id = "btnSearch"
       value = "Search"
       onclick = "doSomething();"
/>
click below button to copy the code. By JavaScript tutorial team

Solution 4:

<input type="text" id="txtSearch" onkeypress="return searchKeyPress(event);" />
<input type="button" id="btnSearch" Value="Search" onclick="doSomething();" />

<script>
function searchKeyPress(e)
{
    // look for window.event in case event isn't passed in
    e = e || window.event;
    if (e.keyCode == 13)
    {
        document.getElementById('btnSearch').click();
        return false;
    }
    return true;
}
</script>
click below button to copy the code. By JavaScript tutorial team

Solution 5:

Make the button a submit element, so it'll be automatic.

<input type = "submit"
       id = "btnSearch"
       value = "Search"
       onclick = "return doSomething();"
/>
click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Trigger a button click with JavaScript on the Enter key in a text box