문제

<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