如何防止在基于web的应用程序中按ENTER键提交表单?


当前回答

在我的案例中,这个jQuery JavaScript解决了这个问题

jQuery(function() {
            jQuery("form.myform").submit(function(event) {
               event.preventDefault();
               return false;
            });
}

其他回答

I Have come across this myself because I have multiple submit buttons with different 'name' values, so that when submitted they do different things on the same php file. The enter / return button breaks this as those values aren't submitted. So I was thinking, does the enter / return button activate the first submit button in the form? That way you could have a 'vanilla' submit button that is either hidden or has a 'name' value that returns the executing php file back to the page with the form in it. Or else a default (hidden) 'name' value that the keypress activates, and the submit buttons overwrite with their own 'name' values. Just a thought.

另一种方法是仅在表单应该提交时才将提交输入按钮附加到表单,并在表单填充期间将其替换为简单的div

//Turn off submit on "Enter" key

$("form").bind("keypress", function (e) {
    if (e.keyCode == 13) {
        $("#btnSearch").attr('value');
        //add more buttons here
        return false;
    }
});

你会发现这更简单和有用:D

$(document).on('submit', 'form', function(e){
    /* on form submit find the trigger */
    if( $(e.delegateTarget.activeElement).not('input, textarea').length == 0 ){
        /* if the trigger is not between selectors list, return super false */
        e.preventDefault();
        return false;
    } 
});

我在这里或其他帖子中找到的所有关于这个主题的答案都有一个缺点,那就是它阻止了表单元素上的实际更改触发器。所以如果你运行这些解决方案,onchange事件也不会被触发。为了克服这个问题,我修改了这些代码,并为自己开发了以下代码。我希望这对其他人有用。 我给了一个类我的表单“prevent_auto_submit”,并添加以下JavaScript:

$(document).ready(function() 
{
    $('form.prevent_auto_submit input,form.prevent_auto_submit select').keypress(function(event) 
    { 
        if (event.keyCode == 13)
        {
            event.preventDefault();
            $(this).trigger("change");
        }
    });
});