搜索字段中的最大字符数

时间:2022-09-13 09:35:48

I have search field and it doesn't have that typical submit button. It looks like this: 搜索字段中的最大字符数

我有搜索字段,它没有典型的提交按钮。它看起来像这样:

HTML:

HTML:

<div class="input-group">
    <input type="text" class="form-control" name="keyword" id="searchbox" onkeypress="return checkLength()"/>
    <span class="btn btn-primary input-group-addon" onclick="checkLength()"><i class="fa fa-search"></i></span>
</div> 

I only added a span and not the input element for submit button. How do I validate if the user types or inputs not less than 2 characters? If the user types in 1 character only then presses that search button or just hit the enter key, there should be a red error message at the bottom of the search field saying "Keyword should be not less than 2 characters" or something like that.

我只添加了span,而没有添加submit按钮的输入元素。如何验证用户输入或输入不少于2个字符?如果用户只输入一个字符,然后按下搜索按钮或按下enter键,那么在搜索字段的底部应该有一个红色的错误消息,说“关键字不应该小于两个字符”或类似的东西。

I tried this code but it's not working:

我试过这段代码,但它不起作用:

function checkLength(){
    var textbox = document.getElementById("searchbox");
    if(textbox.value.length <= 10 && textbox.value.length >= 2){
        alert("success");
    } else {
        alert("Keyword should be not less than 2 characters");
        $(document).keypress(function (e) {
            var keyCode = (window.event) ? e.which : e.keyCode;
            if (keyCode && keyCode == 13) {
                e.preventDefault();
                return false;
            }
        });
    }
}

Need help. Thanks.

需要帮助。谢谢。

EDIT:

编辑:

After inputting keywords and hit the enter key, the page would redirect to a search results page, but that should be prevented from happening if the inputted keyword does not have 2 or more characters, hence, displaying a red text error message below the search field. How to do it?

输入关键字并按下enter键后,页面将重定向到搜索结果页面,但如果输入的关键字没有两个或更多字符,则应避免发生这种情况,因此在搜索字段下方显示红色文本错误消息。如何去做?

4 个解决方案

#1


7  

You can use pattern attribute in HTML5 input, and you can validate the text with just CSS:

可以在HTML5输入中使用pattern属性,只需CSS即可验证文本:

.error {
  display: none;
  font: italic medium sans-serif;
  color: red;
}
input[pattern]:required:invalid ~ .error {
  display: block;
}
<form>
  <input type="text" name="pattern-input" pattern=".{2,}" title="Min 2 characters" required>
  <input type="submit">
  <span class="error">Enter at least two characters</span>
</form>

Here is the Fiddle

这是小提琴

Note: This would work with all modern browsers, IE9 and earlier doesn't seems to have support for :invalid, :valid, and :required CSS pseudo-classes till now and Safari have only partial support.

注意:这将适用于所有现代浏览器,IE9和更早的版本似乎不支持:invalid,:valid,和:到目前为止需要的CSS伪类,Safari只有部分支持。

#2


1  

Jquery Validation plugin can be used. it is very simple.

可以使用Jquery验证插件。它是非常简单的。

$(document).ready(function(){
    $("#registerForm").validate();
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<form id='registerForm' name='registerForm' method='post' action='' >   <p>
   Search <input type='text' name='name' id='name'  minlength="2"     class='required' />
   </p>
</form>

搜索字段中的最大字符数

Ref : http://jqueryvalidation.org/documentation/

裁判:http://jqueryvalidation.org/documentation/

#3


1  

Try utilizing .previousElementSibling to select span .nodeName to select input set div .innerHTML to empty string "" or "Keyword should be not less than 2 characters" , using input event

尝试使用.previousElementSibling来选择span .nodeName来选择input set div .innerHTML来空字符串“”或“关键字不应该小于2个字符”,使用input event

var msg = document.getElementById("msg");

function checkLength(elem) {
  var el = elem.type === "text" ? elem : elem.previousElementSibling
  , len = el.value.length < 2;
  msg.innerHTML = len ? "Keyword should be not less than 2 characters" : "";
  $(el).one("input", function() {
    checkLength(this)
  })
}
#msg {
  color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="input-group">
  <form>
    <input type="text" class="form-control" name="keyword" id="searchbox" />
    <input type="button" class="btn btn-primary input-group-addon" onclick="checkLength(this)" value="X" />
  <div id="msg"></div>
  </form>
</div>

#4


0  

I made a jsfiddle that might be close to what you want.

我做了一个可能接近你想要的。

Take a gander and see what you can make of it.

看看你能做些什么。

Don't hesitate to ask questions about it.

不要犹豫,问一些有关它的问题。

My best explanation is:

我的最好的解释是:

There is an event handler on both the input and the submit button that test the input's value. Based on the conditions that I have assumed from your question, either a success alert or an error message is shown. The success alert could be replaced with an ajax call or to trigger a form submission.

在输入和submit按钮上都有一个事件处理程序,用于测试输入的值。根据我从您的问题中假设的条件,将显示成功警报或错误消息。可以用ajax调用或触发表单提交替换成功警报。

#1


7  

You can use pattern attribute in HTML5 input, and you can validate the text with just CSS:

可以在HTML5输入中使用pattern属性,只需CSS即可验证文本:

.error {
  display: none;
  font: italic medium sans-serif;
  color: red;
}
input[pattern]:required:invalid ~ .error {
  display: block;
}
<form>
  <input type="text" name="pattern-input" pattern=".{2,}" title="Min 2 characters" required>
  <input type="submit">
  <span class="error">Enter at least two characters</span>
</form>

Here is the Fiddle

这是小提琴

Note: This would work with all modern browsers, IE9 and earlier doesn't seems to have support for :invalid, :valid, and :required CSS pseudo-classes till now and Safari have only partial support.

注意:这将适用于所有现代浏览器,IE9和更早的版本似乎不支持:invalid,:valid,和:到目前为止需要的CSS伪类,Safari只有部分支持。

#2


1  

Jquery Validation plugin can be used. it is very simple.

可以使用Jquery验证插件。它是非常简单的。

$(document).ready(function(){
    $("#registerForm").validate();
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<form id='registerForm' name='registerForm' method='post' action='' >   <p>
   Search <input type='text' name='name' id='name'  minlength="2"     class='required' />
   </p>
</form>

搜索字段中的最大字符数

Ref : http://jqueryvalidation.org/documentation/

裁判:http://jqueryvalidation.org/documentation/

#3


1  

Try utilizing .previousElementSibling to select span .nodeName to select input set div .innerHTML to empty string "" or "Keyword should be not less than 2 characters" , using input event

尝试使用.previousElementSibling来选择span .nodeName来选择input set div .innerHTML来空字符串“”或“关键字不应该小于2个字符”,使用input event

var msg = document.getElementById("msg");

function checkLength(elem) {
  var el = elem.type === "text" ? elem : elem.previousElementSibling
  , len = el.value.length < 2;
  msg.innerHTML = len ? "Keyword should be not less than 2 characters" : "";
  $(el).one("input", function() {
    checkLength(this)
  })
}
#msg {
  color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="input-group">
  <form>
    <input type="text" class="form-control" name="keyword" id="searchbox" />
    <input type="button" class="btn btn-primary input-group-addon" onclick="checkLength(this)" value="X" />
  <div id="msg"></div>
  </form>
</div>

#4


0  

I made a jsfiddle that might be close to what you want.

我做了一个可能接近你想要的。

Take a gander and see what you can make of it.

看看你能做些什么。

Don't hesitate to ask questions about it.

不要犹豫,问一些有关它的问题。

My best explanation is:

我的最好的解释是:

There is an event handler on both the input and the submit button that test the input's value. Based on the conditions that I have assumed from your question, either a success alert or an error message is shown. The success alert could be replaced with an ajax call or to trigger a form submission.

在输入和submit按钮上都有一个事件处理程序,用于测试输入的值。根据我从您的问题中假设的条件,将显示成功警报或错误消息。可以用ajax调用或触发表单提交替换成功警报。