Вопрос

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

Это было полезно?

Решение

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>

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top