【问题标题】:How to submit a form on the key press and input value?如何在按键上提交表单并输入值?
【发布时间】:2015-01-27 09:02:48
【问题描述】:

我有一个包含用于搜索的文本输入的表单。我想在用户点击输入文本时提交表单,如果它的值不为空或等于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>

【问题讨论】:

    标签: javascript jquery forms


    【解决方案1】:

    首先,您不希望在任何时候都将“搜索...”作为输入框的/value/。这些天你使用placeholder 属性,像这样:

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

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

    您无需包含任何 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();
        }
      }
    });
    

    小提琴:http://jsfiddle.net/o6fn7eor/1/

    (我冒昧地使用了 jQuery,因为你用它标记了你的问题)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-07
      • 1970-01-01
      • 1970-01-01
      • 2013-06-14
      • 2011-01-26
      • 2015-05-16
      • 2020-10-06
      • 1970-01-01
      相关资源
      最近更新 更多