0

I have a script which is almost complete but I can't figure out the last bit here. The script is meant to limit the amount of words that can be entered into a text area and if they go over the word limit these extra words are removed. I have the amount of words beyond the max labeled as overage. For instance, if you were to enter in 102 words, then the overage would be 2. How would I remove those two words from the text area?

jQuery(document).ready(function($) {
    var max = 100;
    $('#text').keyup(function(e) {
        if (e.which < 0x20) {
            return;
        }

        var value = $('#text').val();
        var regex = /\s+/gi;
        var wordCount = value.trim().replace(regex, ' ').split(' ').length;

        if (wordCount == max) {
            // Reached max, prevent additional.
            e.preventDefault();
        } else if (wordCount > max) {


            <!--Edited to show code from user3003216-->
            <!--Isn't working like this, textarea doesn't update.-->

            var overage = wordCount - max;
            var words = value.split(' ');
            for(var i = 0; i<overage; i++){
                words.pop();
            }

        }
    });         
});
nbrooks
  • 18,126
  • 5
  • 54
  • 66

5 Answers5

0

well it would be better to use java script so here you go:

var maxWords = 20;
event.rc = true;
var words = event.value.split(" ");
if (words.length>maxWords) {
    app.alert("You may not enter more than " + maxWords + " words in this field.");
    event.rc = false;
}
royhowie
  • 11,075
  • 14
  • 50
  • 67
thesonyman101
  • 791
  • 7
  • 16
  • I'm not interested in using alerts. My goal is to remove the additional words over the maximum. Not alert that it is over the maximum. – user1727423 Jul 19 '14 at 18:53
0

You can put below code into your else if statement..

else if (wordCount > max) {
    var overage = wordCount - max;
    var words = value.split(' ');
    for(var i = 0; i<overage; i++){
        words.pop();
    }
}

And if you want to get your string back from that words, you can use join like below:

str = words.join(' ');
Bla...
  • 7,228
  • 7
  • 27
  • 46
  • That's not really working for me. I play around with it and I just don't understand how to get the modified text back into the text area. I added your code to the original post to show how I put it in. I tried the str = words.join(' '); and that doesn't seem to do anything for me. – user1727423 Jul 19 '14 at 18:42
  • Hmm.. If you really compare my answer with @luxelin, you can see that both of use use `.pop()` and `.join()`.. Maybe you said nothing changes because in my answer I put it into variable `str`, not the `textarea` which is like this, ` $('#text').val(words.join());`.. – Bla... Jul 20 '14 at 02:27
0

The easiest way to approach this is just to count the number of words on keypress and go from there. Check whether there are more words than the amount allowed. If so, remove all the excess words: while (text.length > maxWords). Then just replace the value of the text box with the updated text.

fiddle

JavaScript

var maxWords = 10;
$("#myText").keypress(function (event) {
    var text = $(this).val().split(" ");    // grabs the text and splits it
    while (text.length > maxWords) {        // while more words than maxWords
        event.preventDefault();
        text.pop();    // remove the last word
        // event.preventDefault() isn't absolutely necessary,
        // it just slightly alters the typing;
        // remove it to see the difference
    }
    $(this).val(text.join(" "));    // replace the text with the updated text
})

HTML

<p>Enter no more than 10 words:</p>
<textarea id="myText"></textarea>

CSS

textarea {
    width: 300px;
    height: 100px;     
}

You can easily test whether it works by pasting more than maxWords—in this case, 10—words into the textarea and pressing space. All the extra words will be removed.

Community
  • 1
  • 1
royhowie
  • 11,075
  • 14
  • 50
  • 67
  • Oh wow, this is so much more simple then what I was trying to do. Thanks a lot! Oh, btw, you left a ; out at the end. – user1727423 Jul 19 '14 at 19:25
  • @user1727423 Where? Are you referring to the end of the `$("#myText").keypress()` block? A semi-colon isn't necessary there, or anywhere, in javascript, for that matter (other than maybe `for` loops). – royhowie Jul 19 '14 at 19:31
  • Semi-colons are required for separating statements and method calls (like the call to `keypress`), but not for function definitions. JS interpreters don't mind if you leave it out at the end of a line, but if your JS file were minified (as many are when deployed to a Prod server), then whitespace is removed to reduce file size. Then your code would produce syntax errors because of the lack of semi-colon(s). – nbrooks Jul 19 '14 at 21:46
  • @nbrooks minifiers typically do [automatic semicolon insertion](https://code.google.com/p/closure-compiler/issues/detail?id=6), though, so… Personally, I tend to put semicolons after everything but function declarations, which, as you mentioned, are not necessary anyway. – royhowie Jul 19 '14 at 21:53
  • @Luxelin Interesting! That I didn't know (although it makes sense). Either way I feel like it's a safer habit to just do it yourself rather than relying on that...if there were a bug there debugging would be a nightmare `:)`. I take your point though, thanks. – nbrooks Jul 19 '14 at 21:58
  • 1
    @nbrooks Another good habit (for production) is to start all of your js files (ones that will be used on the front-end) with a semicolon. This ensures that they won't interfere with one another. – royhowie Jul 19 '14 at 22:02
0

jsFiddle Demo

You can use val to re-value the text-box. The array slice method will allow you to pull the first 100 words out of the array. Then just join them with a space and stick them back in the text-box.

$(document).ready(function($) {
    var max = 100;

    $('#text').keyup(function(e) {

        if (e.which < 0x20) {
            return;
        }

        var value = $('#text').val();
        var words = value.trim().split(/\s+/gi);
        var wordCount = words.length;

        if (wordCount == max) {
            // Reached max, prevent additional.
            e.preventDefault();
        } else if (wordCount > max) {
            var substring = words.slice(0, max).join(' ');
            $("#text").val(substring + ' ');
        }
    });         
});
nbrooks
  • 18,126
  • 5
  • 54
  • 66
0

While you've already accepted an answer I thought I might be able to offer a slightly more refined version:

function limitWords(max){
    // setting the value of the textarea:
    $(this).val(function(i,v){
    // i: the index of the current element in the collection,
    // v: the current (pre-manipulation) value of the element.

    // splitting the value by sequences of white-space characters,
    // turning it into an Array. Slicing that array taking the first 10 elements,
    // joining these words back together with a single space between them:
        return v.split(/\s+/).slice(0,10).join(' ');
    });
}

$('#demo').on('keyup paste input', limitWords);

JS Fiddle demo.

References:

David Thomas
  • 249,100
  • 51
  • 377
  • 410