最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - OnKeyPress ENTER Reloads The Page - Stack Overflow

programmeradmin3浏览0评论
<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.

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

Share Improve this question asked Oct 8, 2012 at 12:00 shadyinsideshadyinside 6301 gold badge8 silver badges23 bronze badges 4
  • do you have any buttons on the page? Maybe they are getting called? – Daniel Casserly Commented Oct 8, 2012 at 12:01
  • is this code inside any form?. form automatically get submitted when you press enter button on any of its fields. you can prevent it by returning false onkeypress – Anoop Commented Oct 8, 2012 at 12:03
  • yes i have but all the button' type is set to 'button' – shadyinside Commented Oct 8, 2012 at 12:03
  • @Shusl...yes its inside a form.i have called many functions but none one them gets the page reloaded but just this one does. – shadyinside Commented Oct 8, 2012 at 12:04
Add a ment  | 

2 Answers 2

Reset to default 5

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

发布评论

评论列表(0)

  1. 暂无评论