How to capture Enter key press? [duplicate]
Asked Answered
S

11

73

In my HTML page, I had a textbox for user to input keyword for searching. When they click the search button, the JavaScript function will generate a URL and run in new window.

The JavaScript function work properly when the user clicks the search button by mouse, but there is no response when the user presses the ENTER key.

function searching(){
    var keywordsStr = document.getElementById('keywords').value;
    var cmd ="http://XXX/advancedsearch_result.asp?language=ENG&+"+ encodeURI(keywordsStr) + "&x=11&y=4";
    window.location = cmd;
}
<form name="form1" method="get">
    <input name="keywords" type="text" id="keywords" size="50" >
    <input type="submit" name="btn_search" id="btn_search" value="Search" 
        onClick="javascript:searching(); return false;" onKeyPress="javascript:searching(); return false;">
    <input type="reset" name="btn_reset" id="btn_reset" value="Reset">
</form>
Stradivarius answered 21/12, 2012 at 9:18 Comment(2)
Hope this will help you. https://mcmap.net/q/275459/-onkeypress-on-a-lt-a-gt-tagWeatherley
The javascript: shoudl not be used in the onClick or onKeyPress attributesRoutinize
R
118

Form approach

As scoota269 says, you should use onSubmit instead, cause pressing enter on a textbox will most likey trigger a form submit (if inside a form)

<form action="#" onsubmit="handle">
    <input type="text" name="txt" />
</form>

<script>
    function handle(e){
        e.preventDefault(); // Otherwise the form will be submitted

        alert("FORM WAS SUBMITTED");
    }
</script>

Textbox approach

If you want to have an event on the input-field then you need to make sure your handle() will return false, otherwise the form will get submitted.

<form action="#">
    <input type="text" name="txt" onkeypress="handle(event)" />
</form>

<script>
    function handle(e){
        if(e.keyCode === 13){
            e.preventDefault(); // Ensure it is only this code that runs

            alert("Enter was pressed was presses");
        }
    }
</script>
Routinize answered 21/12, 2012 at 9:42 Comment(5)
Error page while accessing JSFiddleCannelloni
Weird.. But the JS-Fiddle did only for his specific scenario. The code examples in the answer is the main idea..Routinize
You need to pass the event as a parameter. <input type="text" name="txt" onkeypress="handle(event)" />Kurrajong
thanks @Routinize for this Idea.Arteriotomy
Please note that e.keyCode is deprecated developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCodeForetaste
E
39

Use onkeypress . Check if the pressed key is enter (keyCode = 13). if yes, call the searching() function.

HTML

<input name="keywords" type="text" id="keywords" size="50"  onkeypress="handleKeyPress(event)">

JAVASCRIPT

function handleKeyPress(e){
 var key=e.keyCode || e.which;
  if (key==13){
     searching();
  }
}

Here is a snippet showing it in action:

document.getElementById("msg1").innerHTML = "Default";
function handle(e){
 document.getElementById("msg1").innerHTML = "Trigger";
 var key=e.keyCode || e.which;
  if (key==13){
     document.getElementById("msg1").innerHTML = "HELLO!";
  }
}
<input type="text" name="box22" value="please" onkeypress="handle(event)"/>
<div id="msg1"></div>
Enunciation answered 21/12, 2012 at 9:22 Comment(2)
It did not work for me either what could be the reason?Alixaliza
Sorry for late reply. The issue is because javascript is not ready by the time windows get loaded. You can either use document.ready function (of jquery). or select "no wrap-in body" dropdown option in javascript settings and it should work. Here is the fiddle jsfiddle.net/Ezrwe/35 .Enunciation
B
13

Use event.key instead of event.keyCode!

function onEvent(event) {
    if (event.key === "Enter") {
        // Submit form
    }
};

Mozilla Docs

Supported Browsers

Buckler answered 5/9, 2017 at 21:34 Comment(2)
This is helpful, but not currently a complete answer. Could you flesh it out with full context?Vouch
@Vouch event.keyCode is deprecated and event.key is now preferredYablon
I
7

Try this....

HTML inline

onKeydown="Javascript: if (event.keyCode==13) fnsearch();"
or
onkeypress="Javascript: if (event.keyCode==13) fnsearch();"

JavaScript

<script>
function fnsearch()
{
   alert('you press enter');
}
</script>
Interstitial answered 25/9, 2013 at 7:10 Comment(0)
M
5

You can use javascript

ctl.attachEvent('onkeydown', function(event) {

        try {
            if (event.keyCode == 13) {
                FieldValueChanged(ctl.id, ctl.value);
            }
            false;
        } catch (e) { };
        return true
    })
Manifold answered 6/9, 2013 at 10:14 Comment(0)
G
4

Small bit of generic jQuery for you..

$('div.search-box input[type=text]').on('keydown', function (e) {
    if (e.which == 13) {
        $(this).parent().find('input[type=submit]').trigger('click');
        return false;
     }
});

This works on the assumes that the textbox and submit button are wrapped on the same div. works a treat with multiple search boxes on a page

Gearldinegearshift answered 12/11, 2013 at 14:28 Comment(0)
D
2

You need to create a handler for the onkeypress action.

HTML

<input name="keywords" type="text" id="keywords" size="50" onkeypress="handleEnter(this, event)" />

JS

function handleEnter(inField, e)
{
    var charCode;

    //Get key code (support for all browsers)
    if(e && e.which)
    {
        charCode = e.which;
    }
    else if(window.event)
    {
        e = window.event;
        charCode = e.keyCode;
    }

    if(charCode == 13)
    {
       //Call your submit function
    }
}
Departure answered 21/12, 2012 at 9:25 Comment(1)
Tried it with a JSFiddle, but it didn't work for me. jsfiddle.net/94jsvConflux
F
1

Use an onsubmit attribute on the form tag rather than onclick on the submit.

Flavorful answered 21/12, 2012 at 9:21 Comment(0)
E
1

	// jquery press check by Abdelhamed Mohamed


    $(document).ready(function(){
    $("textarea").keydown(function(event){
        if (event.keyCode == 13) {
         // do something here
         alert("You Pres Enter");
        }
       });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <textarea></textarea>
Elastic answered 24/8, 2016 at 7:53 Comment(1)
I love the fact that you felt that this incredibly simple piece of code was worthy of attribution!Ivoryivorywhite
T
0
<form action="#">
    <input type="text" id="txtBox" name="txt" onkeypress="handle" />
</form>






<script>
    $("#txtBox").keypress(function (e) {
            if (e.keyCode === 13) {
                alert("Enter was pressed was presses");
            }

            return false;
        });

    </script>
Tzar answered 7/8, 2014 at 11:33 Comment(0)
S
-1

This is simple ES-6 style answer. For capturing an "enter" key press and executing some function

<input
    onPressEnter={e => (e.keyCode === 13) && someFunc()}
/>
Stainless answered 9/4, 2019 at 14:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.