jquery在输入时禁用表单提交

时间:2022-11-23 17:32:54

I have the following javascript in my page which does not seem to be working.

我的页面中有如下的javascript,它似乎不能工作。

$('form').bind("keypress", function(e) {
  if (e.keyCode == 13) {               
    e.preventDefault();
    return false;
  }
});

I'd like to disable submitting the form on enter, or better yet, to call my ajax form submit. Either solution is acceptable but the code I'm including above does not prevent the form from submitting.

我想禁用在enter提交表单,或者更好的是,调用我的ajax表单submit。任何一个解决方案都是可以接受的,但是我所包含的代码并不能阻止表单提交。

16 个解决方案

#1


338  

If keyCode is not caught, catch which:

如果没有捕获关键代码,捕获哪个:

$('#formid').on('keyup keypress', function(e) {
  var keyCode = e.keyCode || e.which;
  if (keyCode === 13) { 
    e.preventDefault();
    return false;
  }
});

EDIT: missed it, it's better to use keyup instead of keypress

编辑:错过了,最好使用keyup而不是keypress

EDIT 2: As in some newer versions of Firefox the form submission is not prevented, it's safer to add the keypress event to the form as well. Also it doesn't work (anymore?) by just binding the event to the form "name" but only to the form id. Therefore I made this more obvious by changing the code example appropriately.

编辑2:在Firefox的一些新版本中,表单提交并没有被阻止,更安全的做法是将keypress事件添加到表单中。同样,它也不能通过将事件绑定到表单“name”而仅仅绑定到表单id来工作(还能继续吗?)

EDIT 3: Changed bind() to on()

编辑3:将bind()更改为on()

#2


49  

Usually form is submitted on Enter when you have focus on input elements.

通常表单是在输入元素时提交的。

We can disable Enter key (code 13) on input elements within a form:

我们可以禁用输入键(代码13)在表单中的输入元素上:

$('form input').on('keypress', function(e) {
    return e.which !== 13;
});

DEMO: http://jsfiddle.net/bnx96/325/

演示:http://jsfiddle.net/bnx96/325/

#3


40  

Even shorter:

更短:

$('myform').submit(function() {
  return false;
});

#4


23  

$('form').keyup(function(e) {
  return e.which !== 13  
});

The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input.

该事件。哪个属性规范化的事件。键码和event.charCode。建议观看活动。用于键盘输入。

which docs.

文档。

#5


13  

$(document).on('keyup keypress', 'form input[type="text"]', function(e) {
  if(e.which == 13) {
    e.preventDefault();
    return false;
  }
});

This solution works on all forms on website (also on forms inserted with ajax), preventing only Enters in input texts. Place it in a document ready function, and forget this problem for a life.

此解决方案适用于网站上的所有表单(也适用于使用ajax插入的表单),防止仅输入文本。把它放在一个文档准备函数中,然后一辈子都忘记这个问题。

#6


6  

The overkill of having to capture and test every keystroke for the ENTER key really bugs me, so my solution relies on the following browser behavior:

必须捕获并测试每一个输入键的击键,这让我感到非常困扰,所以我的解决方案依赖于以下浏览器行为:

Pressing ENTER will trigger a click event on the submit button (tested in IE11, Chrome 38, FF 31) ** (ref: http://mattsnider.com/how-forms-submit-when-pressing-enter/ )

按ENTER将触发提交按钮上的单击事件(在IE11、Chrome 38、FF 31中测试)**(参考:http://mattsnider.com/how-forms-submit-when- pres- enter/)

So my solution is to remove the standard submit button (i.e. <input type="submit">) so that the above behavior fails because there's no submit button to magically click when ENTER is pressed. Instead, I use a jQuery click handler on a regular button to submit the form via jQuery's .submit() method.

因此,我的解决方案是删除标准的submit按钮(即),使上述行为失败,因为在按下ENTER时没有提交按钮魔术般地单击。相反,我在常规按钮上使用jQuery单击处理程序通过jQuery的.submit()方法提交表单。

<form id="myform" method="post">
  <input name="fav_color" type="text">
  <input name="fav_color_2" type="text">
<button type="button" id="form-button-submit">DO IT!</button>
</form>

<script>
 $('#form-button-submit').click(function(){
    $('#myform').submit();
  });
</script>

Demo: http://codepen.io/anon/pen/fxeyv?editors=101

演示:http://codepen.io/anon/pen/fxeyv?editors=101

** this behavior is not applicable if the form has only 1 input field and that field is a 'text' input; in this case the form will be submitted upon ENTER key even if no submit button is present in the HTML markup (e.g. a search field). This has been standard browser behavior since the 90s.

**如果表单只有1个输入字段,且该字段是“文本”输入,则此行为不适用;在这种情况下,表单将在输入键时提交,即使HTML标记中没有提交按钮(例如搜索字段)。这是自90年代以来的标准浏览器行为。

#7


3  

if you just want to disable submit on enter and submit button too use form's onsubmit event

如果您只是想要禁用提交在enter和submit按钮上也使用表单的onsubmit事件

<form onsubmit="return false;">

You can replace "return false" with call to JS function that will do whatever needed and also submit the form as a last step.

您可以将“return false”替换为对JS函数的调用,该函数将执行任何需要的操作,并将表单作为最后一步提交。

#8


3  

I don't know if you already resolve this problem, or anyone trying to solve this right now but, here is my solution for this!

我不知道你是否已经解决了这个问题,或者有人正在试图解决这个问题,但是,这是我的解决方法!

$j(':input:not(textarea)').keydown(function(event){
    var kc = event.witch || event.keyCode;
    if(kc == 13){
    event.preventDefault();
        $j(this).closest('form').attr('data-oldaction', function(){
            return $(this).attr('action');
        }).attr('action', 'javascript:;');

        alert('some_text_if_you_want');

        $j(this).closest('form').attr('action', function(){
            return $(this).attr('data-oldaction');
        });
        return false;
    }
});

#9


3  

You can do this perfectly in pure Javascript, simple and no library required. Here it is my detailed answer for a similar topic: Disabling enter key for form

您可以在纯Javascript中完美地做到这一点,简单且不需要任何库。这里是我对类似主题的详细回答:禁用表单的enter键

In short, here is the code:

简而言之,下面是代码:

<script type="text/javascript">
window.addEventListener('keydown',function(e){if(e.keyIdentifier=='U+000A'||e.keyIdentifier=='Enter'||e.keyCode==13){if(e.target.nodeName=='INPUT'&&e.target.type=='text'){e.preventDefault();return false;}}},true);
</script>

This code is to prevent "Enter" key for input type='text' only. (Because the visitor might need to hit enter across the page) If you want to disable "Enter" for other actions as well, you can add console.log(e); for your your test purposes, and hit F12 in chrome, go to "console" tab and hit "backspace" on the page and look inside it to see what values are returned, then you can target all of those parameters to further enhance the code above to suit your needs for "e.target.nodeName", "e.target.type" and many more...

此代码是为了防止输入类型='text'的“Enter”键。(因为访问者可能需要点击页面上的enter)如果你想要禁用其他动作的“enter”,你可以添加console.log(e);为了您的测试目的,在chrome中点击F12,进入“控制台”选项卡,点击页面上的“backspace”,查看返回的值,然后您可以针对所有这些参数来进一步增强上面的代码,以满足您对“e.target”的需求。节点名”、“e。target。类型”和更多的……

#10


3  

Most answers above will prevent users from adding new lines in a textarea field. If this is something you want to avoid, you can exclude this particular case by checking which element currently has focus :

上面的大多数答案将阻止用户在textarea字段中添加新行。如果您想避免这种情况,您可以通过检查当前的焦点元素来排除这种情况:

var keyCode = e.keyCode || e.which;
if (keyCode === 13 && !$(document.activeElement).is('textarea')) {
  e.preventDefault();
  return false;
}

#11


1  

The following code will negate the enter key from being used to submit a form, but will still allow you to use the enter key in a textarea. You can edit it further depending on your needs.

下面的代码将取消用于提交表单的enter键,但仍然允许您在textarea中使用enter键。您可以根据需要进一步编辑它。

<script type="text/javascript">
        function stopRKey(evt) {
          var evt = (evt) ? evt : ((event) ? event : null);
          var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
          if ((evt.keyCode == 13) && ((node.type=="text") || (node.type=="radio") || (node.type=="checkbox")) )  {return false;}
        }

        document.onkeypress = stopRKey;
</script> 

#12


1  

In firefox, when you at input and press enter, it will submit it's upper form. The solution is in the will submit form add this:

在firefox中,当您在输入和按enter时,它将提交它的上表。解决方案是在提交表单中添加以下内容:

<input type="submit" onclick="return false;" style="display:none" />

#13


1  

3 years later and not a single person has answered this question completely.

3年后,没有一个人能完全回答这个问题。

The asker wants to cancel the default form submission and call their own Ajax. This is a simple request with a simple solution. There is no need to intercept every character entered into each input.

请求者想要取消默认的表单提交并调用自己的Ajax。这是一个带有简单解决方案的简单请求。不需要拦截输入到每个输入中的每个字符。

Assuming the form has a submit button, whether a <button id="save-form"> or an <input id="save-form" type="submit">, do:

假设表单有提交按钮,无论

$("#save-form").on("click", function () {
    $.ajax({
        ...
    });
    return false;
});

#14


0  

When the file is finished (load complete), the script detect each event for " Entry " key and he disable the event behind.

当文件完成(加载完成)时,脚本会检测每个事件的“Entry”键,并将事件禁用。

<script>
            $(document).ready(function () {
                $(window).keydown(function(event){
                    if(event.keyCode == 13) {
                        e.preventDefault(); // Disable the " Entry " key
                        return false;               
                    }
                });
            });
        </script>

#15


-1  

Complete Solution in JavaScript for all browsers

The code above and most of the solutions are perfect. However, I think the most liked one "short answer" which is incomplete.

上面的代码和大多数解决方案都是完美的。然而,我认为最喜欢的一个“简短回答”是不完整的。

So here's the entire answer. in JavaScript with native Support for IE 7 as well.

这就是整个答案。在JavaScript中也支持IE 7。

var form = document.getElementById("testForm");
form.addEventListener("submit",function(e){e.preventDefault(); return false;});

This solution will now prevent the user from submit using the enter Key and will not reload the page, or take you to the top of the page, if your form is somewhere below.

这个解决方案现在将防止用户使用enter键提交,并且不会重新加载页面,如果您的表单在下面某个地方,也不会将您带到页面的顶部。

#16


-9  

How about this:

这个怎么样:

$(":submit").closest("form").submit(function(){
    $(':submit').attr('disabled', 'disabled');
});

This should disable all forms with submit buttons in your app.

这将禁用应用程序中带有提交按钮的所有表单。

#1


338  

If keyCode is not caught, catch which:

如果没有捕获关键代码,捕获哪个:

$('#formid').on('keyup keypress', function(e) {
  var keyCode = e.keyCode || e.which;
  if (keyCode === 13) { 
    e.preventDefault();
    return false;
  }
});

EDIT: missed it, it's better to use keyup instead of keypress

编辑:错过了,最好使用keyup而不是keypress

EDIT 2: As in some newer versions of Firefox the form submission is not prevented, it's safer to add the keypress event to the form as well. Also it doesn't work (anymore?) by just binding the event to the form "name" but only to the form id. Therefore I made this more obvious by changing the code example appropriately.

编辑2:在Firefox的一些新版本中,表单提交并没有被阻止,更安全的做法是将keypress事件添加到表单中。同样,它也不能通过将事件绑定到表单“name”而仅仅绑定到表单id来工作(还能继续吗?)

EDIT 3: Changed bind() to on()

编辑3:将bind()更改为on()

#2


49  

Usually form is submitted on Enter when you have focus on input elements.

通常表单是在输入元素时提交的。

We can disable Enter key (code 13) on input elements within a form:

我们可以禁用输入键(代码13)在表单中的输入元素上:

$('form input').on('keypress', function(e) {
    return e.which !== 13;
});

DEMO: http://jsfiddle.net/bnx96/325/

演示:http://jsfiddle.net/bnx96/325/

#3


40  

Even shorter:

更短:

$('myform').submit(function() {
  return false;
});

#4


23  

$('form').keyup(function(e) {
  return e.which !== 13  
});

The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input.

该事件。哪个属性规范化的事件。键码和event.charCode。建议观看活动。用于键盘输入。

which docs.

文档。

#5


13  

$(document).on('keyup keypress', 'form input[type="text"]', function(e) {
  if(e.which == 13) {
    e.preventDefault();
    return false;
  }
});

This solution works on all forms on website (also on forms inserted with ajax), preventing only Enters in input texts. Place it in a document ready function, and forget this problem for a life.

此解决方案适用于网站上的所有表单(也适用于使用ajax插入的表单),防止仅输入文本。把它放在一个文档准备函数中,然后一辈子都忘记这个问题。

#6


6  

The overkill of having to capture and test every keystroke for the ENTER key really bugs me, so my solution relies on the following browser behavior:

必须捕获并测试每一个输入键的击键,这让我感到非常困扰,所以我的解决方案依赖于以下浏览器行为:

Pressing ENTER will trigger a click event on the submit button (tested in IE11, Chrome 38, FF 31) ** (ref: http://mattsnider.com/how-forms-submit-when-pressing-enter/ )

按ENTER将触发提交按钮上的单击事件(在IE11、Chrome 38、FF 31中测试)**(参考:http://mattsnider.com/how-forms-submit-when- pres- enter/)

So my solution is to remove the standard submit button (i.e. <input type="submit">) so that the above behavior fails because there's no submit button to magically click when ENTER is pressed. Instead, I use a jQuery click handler on a regular button to submit the form via jQuery's .submit() method.

因此,我的解决方案是删除标准的submit按钮(即),使上述行为失败,因为在按下ENTER时没有提交按钮魔术般地单击。相反,我在常规按钮上使用jQuery单击处理程序通过jQuery的.submit()方法提交表单。

<form id="myform" method="post">
  <input name="fav_color" type="text">
  <input name="fav_color_2" type="text">
<button type="button" id="form-button-submit">DO IT!</button>
</form>

<script>
 $('#form-button-submit').click(function(){
    $('#myform').submit();
  });
</script>

Demo: http://codepen.io/anon/pen/fxeyv?editors=101

演示:http://codepen.io/anon/pen/fxeyv?editors=101

** this behavior is not applicable if the form has only 1 input field and that field is a 'text' input; in this case the form will be submitted upon ENTER key even if no submit button is present in the HTML markup (e.g. a search field). This has been standard browser behavior since the 90s.

**如果表单只有1个输入字段,且该字段是“文本”输入,则此行为不适用;在这种情况下,表单将在输入键时提交,即使HTML标记中没有提交按钮(例如搜索字段)。这是自90年代以来的标准浏览器行为。

#7


3  

if you just want to disable submit on enter and submit button too use form's onsubmit event

如果您只是想要禁用提交在enter和submit按钮上也使用表单的onsubmit事件

<form onsubmit="return false;">

You can replace "return false" with call to JS function that will do whatever needed and also submit the form as a last step.

您可以将“return false”替换为对JS函数的调用,该函数将执行任何需要的操作,并将表单作为最后一步提交。

#8


3  

I don't know if you already resolve this problem, or anyone trying to solve this right now but, here is my solution for this!

我不知道你是否已经解决了这个问题,或者有人正在试图解决这个问题,但是,这是我的解决方法!

$j(':input:not(textarea)').keydown(function(event){
    var kc = event.witch || event.keyCode;
    if(kc == 13){
    event.preventDefault();
        $j(this).closest('form').attr('data-oldaction', function(){
            return $(this).attr('action');
        }).attr('action', 'javascript:;');

        alert('some_text_if_you_want');

        $j(this).closest('form').attr('action', function(){
            return $(this).attr('data-oldaction');
        });
        return false;
    }
});

#9


3  

You can do this perfectly in pure Javascript, simple and no library required. Here it is my detailed answer for a similar topic: Disabling enter key for form

您可以在纯Javascript中完美地做到这一点,简单且不需要任何库。这里是我对类似主题的详细回答:禁用表单的enter键

In short, here is the code:

简而言之,下面是代码:

<script type="text/javascript">
window.addEventListener('keydown',function(e){if(e.keyIdentifier=='U+000A'||e.keyIdentifier=='Enter'||e.keyCode==13){if(e.target.nodeName=='INPUT'&&e.target.type=='text'){e.preventDefault();return false;}}},true);
</script>

This code is to prevent "Enter" key for input type='text' only. (Because the visitor might need to hit enter across the page) If you want to disable "Enter" for other actions as well, you can add console.log(e); for your your test purposes, and hit F12 in chrome, go to "console" tab and hit "backspace" on the page and look inside it to see what values are returned, then you can target all of those parameters to further enhance the code above to suit your needs for "e.target.nodeName", "e.target.type" and many more...

此代码是为了防止输入类型='text'的“Enter”键。(因为访问者可能需要点击页面上的enter)如果你想要禁用其他动作的“enter”,你可以添加console.log(e);为了您的测试目的,在chrome中点击F12,进入“控制台”选项卡,点击页面上的“backspace”,查看返回的值,然后您可以针对所有这些参数来进一步增强上面的代码,以满足您对“e.target”的需求。节点名”、“e。target。类型”和更多的……

#10


3  

Most answers above will prevent users from adding new lines in a textarea field. If this is something you want to avoid, you can exclude this particular case by checking which element currently has focus :

上面的大多数答案将阻止用户在textarea字段中添加新行。如果您想避免这种情况,您可以通过检查当前的焦点元素来排除这种情况:

var keyCode = e.keyCode || e.which;
if (keyCode === 13 && !$(document.activeElement).is('textarea')) {
  e.preventDefault();
  return false;
}

#11


1  

The following code will negate the enter key from being used to submit a form, but will still allow you to use the enter key in a textarea. You can edit it further depending on your needs.

下面的代码将取消用于提交表单的enter键,但仍然允许您在textarea中使用enter键。您可以根据需要进一步编辑它。

<script type="text/javascript">
        function stopRKey(evt) {
          var evt = (evt) ? evt : ((event) ? event : null);
          var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
          if ((evt.keyCode == 13) && ((node.type=="text") || (node.type=="radio") || (node.type=="checkbox")) )  {return false;}
        }

        document.onkeypress = stopRKey;
</script> 

#12


1  

In firefox, when you at input and press enter, it will submit it's upper form. The solution is in the will submit form add this:

在firefox中,当您在输入和按enter时,它将提交它的上表。解决方案是在提交表单中添加以下内容:

<input type="submit" onclick="return false;" style="display:none" />

#13


1  

3 years later and not a single person has answered this question completely.

3年后,没有一个人能完全回答这个问题。

The asker wants to cancel the default form submission and call their own Ajax. This is a simple request with a simple solution. There is no need to intercept every character entered into each input.

请求者想要取消默认的表单提交并调用自己的Ajax。这是一个带有简单解决方案的简单请求。不需要拦截输入到每个输入中的每个字符。

Assuming the form has a submit button, whether a <button id="save-form"> or an <input id="save-form" type="submit">, do:

假设表单有提交按钮,无论

$("#save-form").on("click", function () {
    $.ajax({
        ...
    });
    return false;
});

#14


0  

When the file is finished (load complete), the script detect each event for " Entry " key and he disable the event behind.

当文件完成(加载完成)时,脚本会检测每个事件的“Entry”键,并将事件禁用。

<script>
            $(document).ready(function () {
                $(window).keydown(function(event){
                    if(event.keyCode == 13) {
                        e.preventDefault(); // Disable the " Entry " key
                        return false;               
                    }
                });
            });
        </script>

#15


-1  

Complete Solution in JavaScript for all browsers

The code above and most of the solutions are perfect. However, I think the most liked one "short answer" which is incomplete.

上面的代码和大多数解决方案都是完美的。然而,我认为最喜欢的一个“简短回答”是不完整的。

So here's the entire answer. in JavaScript with native Support for IE 7 as well.

这就是整个答案。在JavaScript中也支持IE 7。

var form = document.getElementById("testForm");
form.addEventListener("submit",function(e){e.preventDefault(); return false;});

This solution will now prevent the user from submit using the enter Key and will not reload the page, or take you to the top of the page, if your form is somewhere below.

这个解决方案现在将防止用户使用enter键提交,并且不会重新加载页面,如果您的表单在下面某个地方,也不会将您带到页面的顶部。

#16


-9  

How about this:

这个怎么样:

$(":submit").closest("form").submit(function(){
    $(':submit').attr('disabled', 'disabled');
});

This should disable all forms with submit buttons in your app.

这将禁用应用程序中带有提交按钮的所有表单。