1

如何防止用户通过按“Enter”键提交联系表?此表单是使用 FormMaster 模块制作的。输入字段的代码如下:

<div id="dnn_ctr1410_FormMaster_ctl_9d6e1fc4341b453f905425dacbefddf2div">
    <label class="SubHead" id="dnn_ctr1410_FormMaster_lbl_ctl_9d6e1fc4341b453f905425dacbefddf2" for="dnn_ctr1410_FormMaster_ctl_9d6e1fc4341b453f905425dacbefddf2">Message*<br></label>
    <textarea class="wsi_contactform_bottomcell" tabindex="1" id="dnn_ctr1410_FormMaster_ctl_9d6e1fc4341b453f905425dacbefddf2" wrap="off" cols="20" rows="2" name="dnn$ctr1410$FormMaster$ctl_9d6e1fc4341b453f905425dacbefddf2"></textarea>
    <span style="display:none;" class="NormalRed" id="dnn_ctr1410_FormMaster_rfv_313f9f05e5224c4e9bbf2bf6808f43c9"><br>Enter your message.</span>
</div>

我使用了以下脚本,但没有任何结果:

$('.wsi_contactform_bottomcell').on('keypress keydown keyup', function (e) {
    if (e.keyCode == 13) {
        e.preventDefault();
    }
});

输入我的意思是键盘上的“输入”键!

4

4 回答 4

1

使用 e.which

有些浏览器使用keyCode,有些使用which. 但是jQuery这是标准化的,所以你不必考虑这一点。你可以选择你喜欢的那个。

if (e.which == 13) {
        e.preventDefault();
    }

参考事件.which

演示

于 2013-10-18T13:32:43.613 回答
0

I've done this in the past and it worked well for me. This will disable any effect by the Enter key for the entire page:

<script language="JavaScript">

function disableEnterKey(e)
{
     var key;    
     if(window.event)
          key = window.event.keyCode;
     else
          key = e.which;

     return (key != 13);
}
</script>

<body onKeyPress="return disableEnterKey(event)">

If you want to disable form submission for a particular input field, call this from the onKeyPress handler of the input field:

<input type="text" name="foo" onKeyPress="return disableEnterKey(event)" >

Edit

For you specifically:

$('.wsi_contactform_bottomcell').on('keypress', disableEnterKey);

If the script is never called then you may be trying to bind the handler too early. If the module hasn't added the textarea yet jQuery will fail silently when the selector returns zero results. If this is the case then you will need to come up with a strategy for determining when the module completes its updates to the DOM before trying to bind the event handler.

于 2013-10-18T13:54:30.867 回答
0

为什么不忽略按键并删除提交按钮。而不是添加一个 this.submit() 按钮。像这样:

<input type="button" value="Submit contactform" onclick="this.submit();">

这将从表单中删除“输入键”功能。

于 2013-10-18T13:34:58.447 回答
0

试试这个,如果元素是动态创建的,你的代码将无法工作,因为元素不存在。

$(document).on("keydown", ".wsi_contactform_bottomcell", function(e) { 
   if (e.keyCode == 13 || e.which == 13) {
    e.preventDefault();
   }
});
于 2013-10-18T14:00:54.933 回答