Prevent ASP.NET textbox within a form from submitting the form

烈酒焚心 提交于 2020-02-24 11:11:12

问题


Here's the page I'm working on:

http://mcstevenswholesale.com/catalog.aspx

The textbox below the catalog allows you to skip to a specific page in the catalog. However, if you hit enter in that textbox rather than clicking the "Go" button, it submits the search function in the upper left column. I thought this would be because the entire page is located within an ASP form, but I don't have the same problem with the email signup box on the right side.

I have tried putting the page number textbox into its own HTML form, and have tried changing the button to an image, a button, and a submit input. None of these have worked. I don't want the page to reload, just the page to flip. I'm fairly new to ASP, so I'm sorry if I'm making a very obvious mistake.

Here's the code for the page number textbox (goToPage is a JS function that flips the catalog page):

<div id="goToPage">
    Go to Page: 
    <input id="pageTextbox" type="text" onkeydown="if (event.keyCode == 13) goToPage();"></input>
    <a onclick="goToPage()" href="#"></a>
</div>

The onkeydown makes the page change work, but it still fires the search function. How do I prevent it from doing that?


回答1:


The default behavior of the enter key is to submit the current form in most (if not all) browsers.

You need to suppress the enter key's default behavior. The proper way to suppress the default behavior is to have the event handler return false.

If goToPage() returns false the simplest solution is the following:

onkeydown="if (event.keyCode == 13) return goToPage();"

If not you can add return false after the call to goToPage();

onkeydown="if (event.keyCode == 13) { goToPage(); return false} "

That will cause the enter key to not submit the form when pressed within the page number text box. If you want to disable it for the entire page see the following:

  • http://webcheatsheet.com/javascript/disable_enter_key.php
  • https://stackoverflow.com/questions/6017350/i-need-javascript-function-to-disable-enter-key



回答2:


Try this:

onkeydown="if (event.keyCode == 13) { goToPage(); return false; }"


来源:https://stackoverflow.com/questions/21267522/prevent-asp-net-textbox-within-a-form-from-submitting-the-form

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!