禁用Enter以提交表单

时间:2022-11-23 22:09:19

I have a form with multiple TextBoxes, Textarea and Buttons. By pressing the ENTER in any text box submits the form. So i want to disable the pressing enter only in text boxes and to enable in text-area and buttons. i found a solution but they were using higher jquery version which were not working with mine jquery version. Below is the code i wrote but its only enables the enter in test area and not in buttons. I only have acces to jquery 1.3.1 or just java script. Please help me to fix this code.

我有一个包含多个TextBox,Textarea和Buttons的表单。通过在任何文本框中按ENTER键提交表单。因此,我想禁用仅在文本框中按下输入并在文本区域和按钮中启用。我找到了一个解决方案,但他们使用的是更高级的jquery版本,这些版本与我的jquery版本不兼容。下面是我编写的代码,但它只允许输入测试区而不是按钮。我只能访问jquery 1.3.1或java脚本。请帮我修复此代码。

$(document).keydown(function(e) {
    var element = e.target.nodeName.toLowerCase();
    var element1 = e.target;
    alert(element1);
    if (element != 'textarea') {
        if (e.keyCode === 13) {
            return false;
        }
    }
});

Here i do not want to completely disable pressing the ENTER. i want to disable it only in textboxes.

在这里,我不想完全禁用按ENTER键。我想只在文本框中禁用它。

2 个解决方案

#1


4  

$(function () {
  $('input[type=text]').keypress(function(event) {
    if (event.keyCode == 13) {
      event.preventDefault();
    }
  });
});

Js Fiddle : https://jsfiddle.net/bikrampahi/f0gxev76/

Js Fiddle:https://jsfiddle.net/bikrampahi/f0gxev76/

#2


0  

Add the following attribute to the form element but only if there are no textareas on the form.

将以下属性添加到表单元素,但仅当表单上没有textareas时。

onkeypress="return event.keyCode != 13;"

Fiddle: https://jsfiddle.net/uffbost5/1/

小提琴:https://jsfiddle.net/uffbost5/1/

#1


4  

$(function () {
  $('input[type=text]').keypress(function(event) {
    if (event.keyCode == 13) {
      event.preventDefault();
    }
  });
});

Js Fiddle : https://jsfiddle.net/bikrampahi/f0gxev76/

Js Fiddle:https://jsfiddle.net/bikrampahi/f0gxev76/

#2


0  

Add the following attribute to the form element but only if there are no textareas on the form.

将以下属性添加到表单元素,但仅当表单上没有textareas时。

onkeypress="return event.keyCode != 13;"

Fiddle: https://jsfiddle.net/uffbost5/1/

小提琴:https://jsfiddle.net/uffbost5/1/