我正在创建一个具有四个textarea表单的网站。每种形式都有字数限制。


textarea1:不超过250个字
textarea2:字数限制为500个
textarea3:不超过500个字
textarea4:不超过250个字


我尝试使用尝试解决此问题时发现的现有示例,但似乎无济于事。

   <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
var maxwords = 250;
//
function check_length(obj, cnt, rem)
{
    var ary = obj.value.split(" "); // doubled spaces will throw this off
    var len = ary.length;
    cnt.innerHTML = len;
    rem.innerHTML = maxwords - 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;
        rem.innerHTML = 0;
        return false;
    }
    return true;
}

</script>


的HTML

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

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


有谁知道解决这个问题的办法?

提前致谢,
汤姆

最佳答案

在您的函数中添加一个额外的参数,并在每个函数调用中将maxWords发送给它:

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


当你叫它的时候,包括最大的单词

<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>


要删除剩余的单词,

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


在您的HTML中,

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

关于javascript - 多个文字区域的字数限制,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11227647/

10-12 13:02