Form submitted twice using submit() on keyup

和自甴很熟 提交于 2019-12-04 12:43:23

Why don't browsers smartly prevent the second form post (like Firefox did in my testing)?

That is the default behavior. What if you didn't have your script and the default behavior was such that the form wouldn't POST on enter.

Should I expect this behavior in all major browsers in all platforms?

Yes

Is there a way to improve this code so I perform the submit using JavaScript, but don't get the form submitted twice?

Use a global mutex variable and set it once the form POSTs - checking it on subsequent POSTs to validate. Or, return false from the keyup handler and stop the event propagation.

Some browsers will interpret an input button as a submit if there is only one button in the form. Just return false in your function to prevent the default behavior from submitting the form.

if ($textbox.val().length > 0 && e.keyCode == 13) {
    $textbox.parent('form').submit();
    return false;
}

Your form is being submitted right after the enter has been pressed (on keydown and before keyup fires) so you can do

$(function() {
    $('#my-textbox').keydown(function(e){
        if(e.keyCode==13) e.preventDefault();
    }); 

    $('#my-textbox').keyup(function(e) {
        e.preventDefault();
        var $textbox = $(this);
        if($textbox.val().length > 0 && e.keyCode == 13) {
           $textbox.parent('form').submit();
        }
     });
 });​

A simple test.

Add boolean variable that would be set to true after first submit and use that variable in your if condition. This would prevent accidental double click.

You should also prevent double submit in the application backend (many web frameworks have built-in mechanism for doing this, it easy to come up with custom solution as well).

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