使用Javascript / jQuery计算字符数

时间:2014-01-16 11:08:20

标签: javascript jquery onkeydown onkeyup

我有以下代码:

PHP

<input style="color:red;font-size:12pt;font-style:italic;" 
    readonly="" type="text" name="q22length" size="3" maxlength="3" value="50"/>
<textarea 
    onkeydown="textCounter(document.frmSurvey.q22,document.frmSurvey.q22length,50);mand();" 
    onkeyup="textCounter(document.frmSurvey.q22,document.frmSurvey.q22length,50)" 
    class="scanwid" name="q22" id="q22" rows="5" cols="">
</textarea>

的Jscript

function textCounter(field,cntfield,maxlimit) {
    if (field.value.length > maxlimit) // if too long...trim it!
    field.value = field.value.substring(0, maxlimit);
    // otherwise, update 'characters left' counter
    else
    cntfield.value = maxlimit - field.value.length;
    }

JsFiddle:http://jsfiddle.net/Lh2UU/

代码应在“输入”选项卡中对数字进行计数,然后阻止用户添加超出限制集的其他字符。但是,它不起作用,我不明白为什么 - 任何建议?

1 个答案:

答案 0 :(得分:2)

方法1:jQuery

看到你有jQuery标记,我将给你一个jQuery解决方案:

$(function() {
    // Define our maximum length
    var maxLength = 50;

    // Our input event handler, which fires when the input changes
    $('textarea.scanwid').on('input', function() {
        // Pull the input text and its length
        var value = this.value,
            length = value.length;

        // Check if the length is greater than the maximum
        if (length > maxLength) {
            // If it is, strip everything after the maximum amount
            this.value = this.value.substring(0, maxLength);

            // Ensure our counter value displays 0 rather than -1
            length = maxLength;
        }

        // Update our counter value
        $('input[name="q22length"]').val(maxLength - length);
    });
});

JSFiddle demo


方法2:HTML和jQuery

值得注意的是,我们可以将maxlength属性粘贴到我们的textarea元素上:

<textarea ... maxlength="50"></textarea>

然后我们可以使用此更新我们的计数器:

$(function() {
    var maxLength = +$('textarea.scanwid').attr('maxlength');

    $('textarea.scanwid').on('input', function() {
        $('input[name="q22length"]').val(maxLength - this.value.length);
    });
});

Second JSFiddle demo