How to capture Enter key press? [duplicate]
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>
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>
Try this....
HTML inline
onKeydown="Javascript: if (event.keyCode==13) fnsearch();"oronkeypress="Javascript: if (event.keyCode==13) fnsearch();"
JavaScript
<script>function fnsearch(){ alert('you press enter');}</script>