日期:2014-05-16  浏览次数:20372 次

js控制文本域输入字数
<p><label>审核意见:</label>
                    <textarea class="bug_text" data-x="" data-y="" title="请填写(字数不多于100个)" name="auOpinion" id="auOpinion"
                              onkeydown="changebyte1(this.value,100,'auOpinion');" onkeyup="changebyte1(this.value,100,'auOpinion');"></textarea>
                    <font style="color: #ff0000">*</font>
                </p>
                <SPAN id="byte1_auOpinion" style="font-size: 12px;">(您还可输入</span><span id="byte2_auOpinion" style="color: #ff0000" style="font-size: 12px;">100</span><span id="byte3_auOpinion" style="font-size: 12px;">/100个字)</SPAN>
                



function changebyte1(value, length,textareaId) {
    var l = strlengthComm(value);
    if (l <= length) {
        document.getElementById("byte2_"+textareaId).innerText = (length - l);
        document.getElementById("byte1_"+textareaId).innerText = "(您还可输入";
        document.getElementById("byte3_"+textareaId).innerText = "/"+length+"字)";
        return true;
    } else {
        document.getElementById("byte2_"+textareaId).innerText = "(输入字数超出范围)";
        document.getElementById("byte1_"+textareaId).innerText = "";
        document.getElementById("byte3_"+textareaId).innerText = "";
        document.getElementById(textareaId).value = substrComm(value, length);
    }
}
function substrComm(str, len) {
    if (!str || !len) {
        return "";
    }
    //预期计数:中文2字节,英文1字节
    var a = 0;
    //循环计数
    var i = 0;
    //临时字串
    var temp = "";
    for (i = 0; i < str.length; i++) {
        //if (str.charCodeAt(i) > 255) {
        //按照预期计数增加2
        //	a += 2;
        //} else {
        a++;
        //}
        //如果增加计数后长度大于限定长度,就直接返回临时字符串
        if (a > len) {
            return temp;
        }
        //将当前内容加到临时字符串
        temp += str.charAt(i);
    }
}

function strlengthComm(str) {
    var l = str.length;
    var n = l;
    //for (var i = 0; i < l; i++) {
    //if (str.charCodeAt(i) < 0 || str.charCodeAt(i) > 255) {
    //		n++;
    //}
    //}
    return n;
}