简体   繁体   English

输入框中的限制词

[英]limit words in input box

I have an input box named "title". 我有一个名为“ title”的输入框。

I want the user to only enter 35 words not more than that. 我希望用户仅输入35个单词。

<input name="title" id="title" class="event-name gui-input" placeholder="Title" type="text">

<script type="text/javascript">
    /* <![CDATA[ */
    jQuery(function(){
        jQuery("#title").validate({
            expression: "if (VAL) return true; else return false;",
            message: "Please enter Title"
        });
    });
</script>

Use the JavaScript split method: 使用JavaScript split方法:

var content = $("input#title").val() //content is now the value of the text box
var words = content.trim().split(/\s+/); //words is an array of words, split by space
var num_words = words.length; //num_words is the number of words in the array

if(num_words>35){
    //too many words
    return false;
}

Hopefully this helps and you can adapt this code to your validation. 希望这会有所帮助,您可以使此代码适合您的验证。

JSFiddle 的jsfiddle


One-line solution to return the number of words in the input: 单行解决方案,返回输入中的单词数:

var num_words = $("input#title").val().trim().split(/\s+/).length;

JSFiddle 的jsfiddle

I have modified the solution provided by Ben. 我已经修改了Ben提供的解决方案。 Providing the user to know how many words are left. 让用户知道还剩下多少个单词。

Script... 脚本...

 $("#title").keyup(function(){

   var content = $("#title").val(); //content is now the value of the text box
   var words = content.split(/\s+/); //words is an array of words, split by space
   var num_words = words.length; //num_words is the number of words in the array
   var max_limit=35;
    if(num_words>max_limit){
        alert("Exceeding the max limit");
        var lastIndex = content.lastIndexOf(" ");
            $("#title").val(content.substring(0, lastIndex));

       $('#remainingChars').text('Limit Exceeding');
        return false;
    }
    else 
    {
    $('#remainingChars').text(max_limit+1-num_words +" words remaining");
    }
    });

Form fields.. 表格栏位

  <input name="title" type="text" id="title" size="100" /> 
    <div id="remainingChars">Max limit is 35 words.</div>

JsFiddle 的jsfiddle

You can write following logic on keyup event 您可以在keyup事件中编写以下逻辑

35 words = 34 spaces 35个字= 34个空格

  1. Create a counter to count number of spaces 创建一个计数器以计算空间数
  2. Just check for (n-1) value of counter where n is Number of words. 只需检查计数器的(n-1)值,其中n是字数。
  3. Display error message in case user is going beyond that. 如果用户超出此范围,则显示错误消息。

Just use max length in input field. 只需在输入字段中使用最大长度即可。

<input name="title" id="title" class="event-name gui-input" 
placeholder="Title" type="text"  maxlength="35">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM