Skip to content Skip to sidebar Skip to footer

Word Limits On Multiple Text Areas

I am creating a website with four textarea forms. Each form has a word limit. textarea1: 250 word limit textarea2: 500 word limit textarea3: 500 word limit textarea4: 250 word li

Solution 1:

Add an extra parameter to your function, and send it the maxWords from each function call:

function check_length(obj, cnt, rem, maxwords)
{
//... rest of the function would stay the same

and when you call it, include the max words

<textarea name="Message 2" onkeypress="
 return check_length(this,
 document.getElementById('count2'),
 document.getElementById('remaining2'), 250);"></textarea>
Word count: <span id="count2">0</span> &nbsp;
Words remaining: <span id="remaining2">500</span>

To remove the words remaining,

function check_length(obj, cnt, maxwords)
{
    var ary = obj.value.split(" "); // doubled spaces will throw this off
    var len = ary.length;
    cnt.innerHTML = len;

    if (len > maxwords) {
        alert("Message in '" + obj.name + "' limited to " + maxwords + " words.");
        ary = ary.slice(0,maxwords-1);
        obj.value = ary.join(" "); // truncate additional words
        cnt.innerHTML = maxwords;
        return false;
    }
    return true;
} 

and in your HTML,

<textarea name="Message 1" onkeypress="
return check_length(this,
document.getElementById('count1'),250);"></textarea>
Word count: <span id="count1">0</span> &nbsp;

Solution 2:

insert a class attribute for those textareas, (like class='area250', class='area500' and so on) then include an if statement in the function

function check_length(obj, cnt, rem)
    {
        if(window.event.srcElement.getAttribute('class')=='area250')
            maxwords=250;
        else if(window.event.srcElement.getAttribute('class')=='area500')
            maxwords=500;
        else .......................................

    } 

Solution 3:

The problem with your function is that you're always checking the amount of words inserted against maxwords variable (which is set to 250 words as the first textarea limit)

so a better attempt is to pass an extra parameter to the function with the original limit (different for each textarea)


Post a Comment for "Word Limits On Multiple Text Areas"