Show how many characters remaining in a HTML text box using JavaScript

ChristineS picture ChristineS · Oct 5, 2012 · Viewed 105.2k times · Source

This is my code:

function textCounter(field, countfield, maxlimit) {
    if (field.value.length > maxlimit) {
        field.value = field.value.substring(0, 160);
        field.blur();
        field.focus();
        return false;
    } else {
        countfield.value = maxlimit - field.value.length;
    }
}

How can I display how many characters are remaining from a certain text box with a limit of 160?

Answer

Nokia808Freak picture Nokia808Freak · Oct 5, 2012

Dynamic HTML element functionThe code in here with a little bit of modification and simplification:

<input disabled  maxlength="3" size="3" value="10" id="counter">
<textarea onkeyup="textCounter(this,'counter',10);" id="message">
</textarea>
<script>
function textCounter(field,field2,maxlimit)
{
 var countfield = document.getElementById(field2);
 if ( field.value.length > maxlimit ) {
  field.value = field.value.substring( 0, maxlimit );
  return false;
 } else {
  countfield.value = maxlimit - field.value.length;
 }
}
</script>

Hope this helps!

tip:

When merging the codes with your page, make sure the HTML elements(textarea, input) are loaded first before the scripts (Javascript functions)