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

javascript - Form submits twice when pressing returnenter - Stack Overflow

programmeradmin3浏览0评论

I'm using anchors as links, and also I'm binding the enter/return key to submit a form, like this:

$("form[name!=smsform]").bind("keyup", function(e){
if(e.keyCode == 13){
$(this).submit();
});

$("a[title=submit]").click( function(){
$(this).parents("form").submit();
});

However the form submits twice when clicking enter/return using the code above, I need to merge the two snippets - anyone know how to go about this?

I'm using anchors as links, and also I'm binding the enter/return key to submit a form, like this:

$("form[name!=smsform]").bind("keyup", function(e){
if(e.keyCode == 13){
$(this).submit();
});

$("a[title=submit]").click( function(){
$(this).parents("form").submit();
});

However the form submits twice when clicking enter/return using the code above, I need to merge the two snippets - anyone know how to go about this?

Share Improve this question asked Feb 19, 2010 at 7:27 timkltimkl 3,33912 gold badges59 silver badges71 bronze badges 1
  • this thread is weird all the answer say prevent but no one give a codes or tell us how to prevent – buncis Commented Feb 20, 2022 at 7:45
Add a ment  | 

3 Answers 3

Reset to default 5

A form will submit automatically when you click enter, there is no need to write the code yourself. If you want to add some testing to the enterkey event before you submit, then you can return false from the callback function to prevent the default browser action.

Usually this means that both your link and the browser's default mechanism are submitting the form. To prevent that, put a handler on the form's submit event that prevents (stops) it (the event is not fired when you submit the form programmatically, so it won't prevent your link sending it).

For example:

document.querySelector("selector-for-your-form").addEventHandler("submit", event => {
    event.preventDefault(); // Prevents submission
});

Try preventing the default action of the enter key before calling the submit.

发布评论

评论列表(0)

  1. 暂无评论