Search code examples
javascriptjqueryonkeydownonkeyup

Counting characters using Javascript/jQuery


I have the following code:

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/

The code should count the number down in the Input tab and then stop the user from adding further characters beyond the limit set. However, it's not working and I can't see why - any suggestions?


Solution

  • Method 1: jQuery

    Seeing as you have jQuery tagged, I'm going to give you a jQuery solution:

    $(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.


    Method 2: HTML and jQuery

    It's also worth noting that we could just stick the maxlength attribute onto our textarea element:

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

    We can then update our counter using this:

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

    Second JSFiddle demo.