Question

<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.

Était-ce utile?

La solution

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>

Autres conseils

I know this is an old message, but I solved it adding "return false":

<input type="text" onkeypress="if (event.keyCode==13){ func_name(this.value);return false;}" id="userinput"/>

Maybe it is usefull to other with a similar issue.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top