简体   繁体   English

如何在textarea HTML中限制单词而不是字符

[英]How can I limit words, not characters, in textarea HTML

I need to control a textarea with 2 clauses, 200 characters and 20 words at most. 我最多需要控制2个子句,200个字符和20个单词的文本区域。

I solved the 200 character limit with a maxlength in the HTML, but I don't know how to limit the text by words. 我用HTML中的maxlength解决了200个字符的限制,但是我不知道如何用词来限制文本。

The code is the following: 代码如下:

<textarea onkeydown="get_textvalue();" onkeyup="ad_writer();" id="mytextarea" name="mytextarea" maxlength="200">

<script>

    function get_textvalue(){

        var ad = $("#mytextarea");

        var ad_words  = ad.val().split(' ').length;
        var ad_length = ad.val().length;

        // Contador de palabras
        $("span#words_counting").text(ad_words);

        if(ad_words == 20){
            $("span#words_counting").css("color", "red");
        }

        if(ad_length >= 180){
            $("div#ad_warning").slideDown();
        }

    }

    function ad_writer(){

        var ad = $("#mytextarea");

        var ad_text   = ad.val();
        var ad_words  = ad_text.split(' ').length;
        var ad_length = ad_text.length;

        if(ad_words == 20){

            var new_ad = ad.val().substring(0,ad_length);
            $("#mytextarea").val(new_ad);

        }

        $("#avis_vendor_id").html(ad_text);

    }

</script>

It seems like you have the basic pieces so far as code is concerned (ie, counting words, etc.). 就代码而言,您似乎已经具备了基本知识(例如,对单词进行计数等)。 I'd recommend you register for the 'input' event on that control, and perform your check then. 我建议您在该控件上注册“输入”事件,然后执行检查。 If the user has too many words, you can trim back the string to the desired content and/or update the UI to reflect the error condition. 如果用户的单词过多,则可以将字符串修整为所需的内容和/或更新UI以反映错误情况。

This function counts the words. 此功能对单词进行计数。

  var wordLen = 255; // Maximum word length
         function checkWordLen(obj){
          var len = obj.value.split(/[\s]+/);
           if(len.length > wordLen){
               alert("You cannot put more than "+wordLen+" words in this text area.");
               obj.oldValue = obj.value!=obj.oldValue?obj.value:obj.oldValue;
               obj.value = obj.oldValue?obj.oldValue:"";
               return false;
           }
         return true;
       }

Then just need to call that function every time that textarea changes. 然后,只需在每次文本区域更改时调用该函数。

<textarea rows="15" cols="30" name="t1" onchange="checkWordLen(this);"></textarea>

Well, first of all you're missing the textarea end tag. 好吧,首先,您缺少textarea结束标签。

And what do you want? 你想要什么? To stop writing when you reached the words limit? 当您达到字数上限时要停止写作吗?

You can do that if you do this: 如果执行以下操作,则可以这样做:

if(ad_words >= 20){
  var words=ad.val().split(' ');
  var words20=words.slice(0,20).join(" ");
  $("#mytextarea").val(words20);
  $("span#words_counting").css("color", "red");
}

Here's a jsFiddle of it in action: http://jsfiddle.net/cyrusaf/79StL/3/ 这是一个实际使用的jsFiddle: http : //jsfiddle.net/cyrusaf/79StL/3/


You can use jQuery to do this very easily. 您可以使用jQuery轻松完成此操作。 You must access the textarea by name not by id. 您必须按名称而不是ID访问文本区域。

Give the <textarea> element a name: <textarea name="mytextarea"></textarea> <textarea>元素命名: <textarea name="mytextarea"></textarea>

And access it by using the selector $('textarea[name=mytextarea]') 并使用选择器$('textarea[name=mytextarea]')访问它

// On textarea change
$('textarea[name=mytextarea]').keyup(function(){
    // Get value of textarea
    var str = $('textarea[name=mytextarea]').val();
    // Check if value has more than 20 words
    if (str.split(' ').length > 20) {
        // Create string with first 20 words
        var str_new = str.split(' ').splice(0, 20).join(' ');
        // Overwrite the content with the first 20 words
        $('textarea[name=mytextarea]').val(str_new);
});

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

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