Vinicius Santana
Vinicius Santana

Reputation: 4106

Multiple textarea remaining words count with javascript

I recently posted a question here and even though I got good answers none solved my problem and so here I am again.

Original question: How to do JavaScript to Count how many remaining words are on a combination of 4 textarea fields

Here is the situation:

I have a page with 5 fields textbox. Considering that the first one has a number of words limit and also that the 4 other have a limit but all together. I need to show the user how many remaining words he still have for the first textbox and for the other 4. Also to don't allow the user to insert more words once the limit is riched.

Here is the closest thing to it that I got working so far. It counts the remaning words but let's the user add extra words. I tried changing the attr of MyTextBox to readonly but then I cant edit once I get to the limit.

Please help. :)

Html

<textarea id="MyTextBox1" class="MyTextBox" cols="60" rows="8"></textarea>
<textarea id="MyTextBox2" class="MyTextBox" cols="60" rows="8"></textarea>
<textarea id="MyTextBox3" class="MyTextBox" cols="60" rows="8"></textarea>
<textarea id="MyTextBox4" class="MyTextBox" cols="60" rows="8"></textarea>
<p><span id="remainingWords"></span> Words Remaining</p>
<p><span id="ExtraWords" style="font-family: Cambria; font-size: large; color: Red;"></span></p>

JavaScript

    var WordsLimit = 10;
    var WordsUsed = 0;
    var WordsRemaining = 10;
    var regex = /\s+/gi;
    $(document).ready(function () {

        $('.MyTextBox').live("keyup", function (e) {
            var v = "";
            $('.MyTextBox').each(function() { v = v + " " + $(this).val().trim(); });
            v = v.trim();
            console.log(v);
            var WordsUsed = v.replace(regex, ' ').split(' ').length;
            WordsRemaining = parseInt(WordsLimit) - parseInt(WordsUsed);
            if (WordsUsed == WordsLimit) {
                $('.MyTextBox').readOnly = true;
                $('#remainingWords').html("0 Words remaining.");
                $('#ExtraWords').html("");

            }
            else if (WordsUsed > WordsLimit) {
                $('#remainingWords').html("0");
                document.getElementById('MyTextBox1').readOnly = true;
                var extraWord = parseInt(WordsUsed) - parseInt(WordsLimit);
                $('#ExtraWords').html("You have entered " + extraWord + " extra Words!!");
            } else {
                $('#remainingWords').html(WordsRemaining);
            }
        });
    });

http://jsfiddle.net/2b6agtt9/

Upvotes: 0

Views: 891

Answers (3)

Hamix
Hamix

Reputation: 1335

A useful plugin for you

JQuery

jQuery.fn.extend({
    lengthLimit: function(limit,disabled,$label,multipleClassName) {
        this.unbind("keyup.keyupTextLimits");
        this.bind("keyup.keyupTextLimits",function() {
            var allSelector=$("."+multipleClassName).add($(this));
            var otherFieldsLength=0;
            allSelector.not(this).each(function() { 
                otherFieldsLength+=this.value.length;
            });
            var val=$(this).val();    
            var len =val.length+otherFieldsLength;
            if (len > limit) {
                allSelector.each(function(){
                    $(this).val(val.substring(0, limit));
                    if(disabled) $(this).attr('readonly','readonly');
                });
            } else {
                $label.text((limit-len)+" Words Remaining");
            }           
        });
        this.trigger("keyup.keyupTextLimits");
        return this;
    }
    });
    $("#MyTextBox1").lengthLimit(20,true,$("#remainingWords1"));
    $(".diff").lengthLimit(20,true,$("#remainingWords2"),"diff");
    $("#reLimit").click(function(){
       $("#MyTextBox1").lengthLimit(10,true,$("#remainingWords1"));
    });

DEMO

Upvotes: 0

Schlaus
Schlaus

Reputation: 19212

Update

Okay, I perhaps went a bit overboard with this, but here's a new fiddle: http://jsfiddle.net/2b6agtt9/10/

Take a look. I think it's what you want. The question how to handle the last word is a bit tricky, but in this example it can be anything as long as it doesn't have a space, tab, enter, dot, or comma. You could append more keycodes to disallow if you like. I'd be happy to explain if parts of the code are not self explanatory.

Old answer follows

Instead of making the textarea read only, you can prevent any other input but backspace:

$('#MyTextBox1').on("keydown", function(e) {
    if (e.keyCode !== 8) {                            
        return false;
    }
});

You should use this when the word limit is reached. Once the word count is lower, you should do

$('#MyTextBox1').off("keydown");

Here's a fiddle to demonstrate: http://jsfiddle.net/2b6agtt9/8/

Upvotes: 1

Isaac
Isaac

Reputation: 983

It count the number of word in the textarea and remove the extra one work with paste and type

$('#remainingWords').html("0");
var extraWord = parseInt(WordsUsed) - parseInt(WordsLimit);
var postBody = $('#MyTextBox1').val().split(' ');
console.log($('#MyTextBox1').val());
for(var i = WordsLimit; i < WordsUsed; i++){
    postBody.pop();
}
$('#MyTextBox1').val(postBody.join(' '));
$('#ExtraWords').html("You have entered " + extraWord + " extra Words!!");

Here is the fiddle http://jsfiddle.net/2b6agtt9/9/

Upvotes: 0

Related Questions