OnKeyPress ENTER Reloads The Page

shadyinside picture shadyinside · Oct 8, 2012 · Viewed 32.6k times · Source
<input type="text" onkeypress="if (event.keyCode==13){ func_name(this.value);}"    id="userinput"/>

I have a textfield where i have called a function on hitting the ENTER key.The problem is that the page gets reloaded while it should not have been so as i am calling only a js function.Please tell me what am i doing wrong.

Answer

Billy Moon picture Billy Moon · Oct 8, 2012

The form is being submitted by the pressing of enter. You can attach an onsubmit event to the form, and return false to prevent submission (and true to submit). YOu can use this feature to validate the data before submitting, or to intercept your keypress event.

Alternatively, as commented on below, you can use event.preventDefault() to prevent the pressing of enter triggering a submit.

Something like this...

<form action=".">
    <input type="text" onkeypress="console.log('happy days'); event.preventDefault()">
</form>