我在一个网站上有一个调查,用户按下回车键(我不知道为什么),不小心没有点击提交按钮就提交了调查(表单),这似乎有些问题。有办法防止这种情况吗?

我在调查中使用HTML, PHP 5.2.9和jQuery。


当前回答

$(document).on("keydown","form", function(event)
{
   node = event.target.nodeName.toLowerCase();
   type = $(event.target).prop('type').toLowerCase();

   if(node!='textarea' && type!='submit' && (event.keyCode == 13 || event.keyCode == 169))
   {
        event.preventDefault();
        return false;
    }
});

它工作得很完美!

其他回答

我想添加一些CoffeeScript代码(没有经过现场测试):

$ ->
    $(window).bind 'keypress', (event) ->
        if event.keyCode == 13
            unless {'TEXTAREA', 'SELECT'}[event.originalEvent.srcElement.tagName]
                event.preventDefault()

(我希望你喜欢这个“除非”从句中的妙招。)

您可以创建一个JavaScript方法来检查是否按下了Enter键,如果按下了,就停止提交。

<script type="text/javascript">
  function noenter() {
  return !(window.event && window.event.keyCode == 13); }
</script>

只需在submit方法上调用它。

一种完全不同的方法:

The first <button type="submit"> in the form will be activated on pressing Enter. This is true even if the button is hidden with style="display:none; The script for that button can return false, which aborts the submission process. You can still have another <button type=submit> to submit the form. Just return true to cascade the submission. Pressing Enter while the real submit button is focussed will activate the real submit button. Pressing Enter inside <textarea> or other form controls will behave as normal. Pressing Enter inside <input> form controls will trigger the first <button type=submit>, which returns false, and thus nothing happens.

因此:

<form action="...">
  <!-- insert this next line immediately after the <form> opening tag -->
  <button type=submit onclick="return false;" style="display:none;"></button>

  <!-- everything else follows as normal -->
  <!-- ... -->
  <button type=submit>Submit</button>
</form>

这将禁用页面上所有表单的输入键,并且不阻止在文本区域输入。

    // disable form submit with enter

    $('form input:not([type="submit"])').keydown((e) => {
        if (e.keyCode === 13) {
            e.preventDefault();
            return false;
        }
        return true;
    });

这对我很有用

jQuery.each($("#your_form_id").find('input'), function(){
    $(this).bind('keypress keydown keyup', function(e){
       if(e.keyCode == 13) { e.preventDefault(); }
    });
});