除非文本字段超过 2 个字符,否则不要提交表单


Don't submit form unless text field has more than 2 characters

我有这个简单的表格用于我的网站搜索(Wordpress)

<form action="/" method="get">
    <label for="search">Search</label>
    <input type="text" name="s" id="search" value="<?php the_search_query(); ?>" />
    <input type="image" class="search-btn" alt="Search" src="<?php bloginfo( 'template_url' ); ?>/img/magnifier13.png" width="16" height="16" />
</form>

不希望人们能够在搜索字段中输入少于 2 个字符的情况下搜索任何内容,我该怎么做?最好使用 JS。

您可以使用

HTML5的pattern属性。还需要 required 属性,否则具有空值的输入字段将从约束验证中排除。

<input pattern=".{2,}"   required title="2 characters minimum">
<input pattern=".{3,10}" required title="3 to 10 characters">

您可以简单地调用javascript代码在提交表单之前检查文本框的长度。

<form action="/" method="get" onsubmit="return (document.getElementById('search').value.length > 2);">

如果长度小于定义的金额,您可以使用表单onsubmit事件来阻止提交:

<form action="/" method="get" onsubmit="return (this.s.value.length > 2);">
    <label for="search">Search</label>
    ...

使用 JavaScript,您可以检查搜索文本框的长度,并查看它是否超过 2 个字符。如果超过 2,请继续搜索:

  document.getElementsByClassName('test').onClick =function(){
        if(document.getElementById('search').text.length <= 2){
            alert("Needs more than two characters to do search);
        else{
            // commence search
        }
    });

你可以简单地做这样的事情:

<form action="/" method="get">
    <label for="search">Search</label>
    <input type="text" name="s" id="search" value="<?php the_search_query(); ?>" />
    <input type="image" class="search-btn" alt="Search" src="<?php bloginfo( 'template_url' ); ?>/img/magnifier13.png" width="16" height="16" />
    <input type='button' onclick='checkBeforeSubmit();'>
</form>

// somewhere in your javascript code:
var checkBeforeSubmit = function(){
    var text = $("#search").val();
    if(text.length > 2)
        $(form).submit();
}
$('#SubmitButtonId').Click(function(){
  var myLength = $("#search").val().length;
  if(myLength < 3)
  {
    //show message
  }
  else
  {
    //submit form
  }
});