如何在按键和输入值上提交表单?

How to submit a form on the key press and input value?

我有一个包含用于搜索的文本输入的表单。如果用户在文本输入中输入的值不为 null 或不等于 Search...,我想提交表单,这是我的代码:

<form 
     action="<?php echo MAIN_URL."search"; ?>" 
     method="post" 
     onkeydown="if (event.keyCode == 13 && this.getElementByName('search').value!='') { this.submit(); }">
    <input type="submit" name="" value="">
    <input type="text" name="search" value="Search..." onclick="if(this.value=='Search...')this.value='';" onblur="if(this.value=='')this.value='Search...';" />
</form>

首先,你真的不想让"Search..."随时作为你输入框的/值/。这些天你使用 placeholder 属性,像这样:

<input type="text" name="search" placeholder="Search...">

浏览器支持各不相同(旧 IE...),但有可用的 polyfill。总体:更清洁、更好的解决方案。

您无需包含任何 JS 即可在 enter 上自动提交您的表单,但这里有一些代码可以防止提交表单,只要您的文本 input 是空:

$(document).keypress(function (e) {
  if (e.which === 13 && $('input[type="text"]').is(':focus')) {
    if ($('input[type="text"]').val().length < 1) {
      e.preventDefault();
    }
  }
});

fiddle: http://jsfiddle.net/o6fn7eor/1/

(我随意使用 jQuery,因为你用它标记了你的问题)