【问题标题】:Counting characters using Javascript/jQuery使用 Javascript/jQuery 计算字符数
【发布时间】:2014-01-16 11:08:20
【问题描述】:

我有以下代码:

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/

代码应在“输入”选项卡中倒数,然后阻止用户添加超出设置限制的更多字符。但是,它不起作用,我不明白为什么 - 有什么建议吗?

【问题讨论】:

    标签: javascript jquery onkeydown onkeyup


    【解决方案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.


    方法二: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.

    【讨论】:

    • 感谢 James - 非常感谢,比现有解决方案优雅得多。
    猜你喜欢
    • 1970-01-01
    • 2011-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多