限制输入框中的单词

时间:2015-10-15 09:48:37

标签: javascript jquery html ajax

我有一个名为“title”的输入框。

我希望用户只输入不超过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>

4 个答案:

答案 0 :(得分:4)

使用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;
}

希望这会有所帮助,您可以根据验证情况调整此代码。

<强> JSFiddle

单行解决方案,用于返回输入中的单词数:

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

<强> JSFiddle

答案 1 :(得分:1)

我修改了Ben提供的解决方案。 让用户知道剩下多少个单词。

脚本...

 $("#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");
    }
    });

表单字段..

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

JsFiddle

答案 2 :(得分:0)

您可以在keyup事件

上编写以下逻辑

35个字= 34个空格

  1. 创建一个计数器以计算空格数
  2. 只需检查计数器的(n-1)值,其中n是单词数。
  3. 如果用户超出此范围,则显示错误消息。

答案 3 :(得分:-1)

只需在输入字段中使用最大长度。

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