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

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?

This question is related to javascript textarea

The answer is


Try this

HTML

<textarea id="textarea" rows="8" cols="50" maxlength="100" ></textarea>
<div id="feedback"></div>

JS

$(document).ready(function() {
        var max = 1000;
        $('#feedback').html(max + 'characters remaining');

        $('#textarea').keyup(function() {
            var text_length = $('#textarea').val().length;
            var text_remaining = max - text_length;

            $('#feedback').html(text_remaining + ' characters remaining');
        });
    });

HTML:

 <form>
  <textarea id='text' maxlength='10'></textarea>
  <div id='msg'>10 characters left</div>
  <div id='lastChar'></div>
</form>

JS:

function charCount() {
  var textEntered = document.getElementById('text').value;
  var msg = document.getElementById('msg');
  var counter = (10-(textEntered.length));
  msg.textContent = counter+' characters left';
}

var el = document.getElementById('text');
el.addEventListener('keyup',charCount,false);

How about this approach, which splits the problem into two parts:

  • Using jQuery, it shows a decrementing counter below the textarea, which turns red when it hits zero but still allows the user to type.
  • I use a separate string length validator (server and client-side) to actually prevent submission of the form if the number of chatacters in the textarea is greater than 160.

My textarea has an id of Message, and the span in which I display the number of remaining characters has an id of counter. The css class of error gets applied when the number of remaining characters hits zero.

var charactersAllowed = 160;

$(document).ready(function () {
    $('#Message').keyup(function () {
        var left = charactersAllowed - $(this).val().length;
        if (left < 0) {
            $('#counter').addClass('error');
            left = 0;
        }
        else {
            $('#counter').removeClass('error');
        }
        $('#counter').text('Characters left: ' + left);
    });
});

You can bind key press event with your input box and returning false if characters are more than 160 will solve the problem jsfiddle.

JavaScript:

$('textarea').keypress(function(){

    if(this.value.length > 160){
        return false;
    }

    $("#remainingC").html("Remaining characters : " + (160 - this.value.length));
});?

HTML

<textarea></textarea>?
<span id='remainingC'></span>

Try the following code for instance:

working code in jsfiddle.net

For textArea, use this:

<textarea id="txtBox"></textarea>
...
...

For textBox, use this:

<input type="text" id="txtBox"/>
<br>
<input type="text" id="counterBox"/>
<script>
 var txtBoxRef = document.querySelector("#txtBox");
 var counterRef = document.querySelector("#counterBox");
 txtBoxRef.addEventListener("keydown",function(){
  var remLength = 0;
  remLength = 160 - parseInt(txtBoxRef.value.length);
  if(remLength < 0)
   {
    txtBoxRef.value = txtBoxRef.value.substring(0, 160);
    return false;
   }
  counterRef.value = remLength + " characters remaining...";
 },true);
</script>

Hope this Helps!


I needed something like that and the solution I gave with the help of jquery is this:

<textarea class="textlimited" data-textcounterid="counter1" maxlength="30">text</textarea>
<span class='textcounter' id="counter1"></span>

With this script:

// the selector below will catch the keyup events of elements decorated with class textlimited and have a maxlength
$('.textlimited[maxlength]').keyup(function(){
     //get the fields limit
    var maxLength = $(this).attr("maxlength");

    // check if the limit is passed
    if(this.value.length > maxLength){
        return false;
    }

    // find the counter element by the id specified in the source input element
    var counterElement = $(".textcounter#" + $(this).data("textcounterid"));
    // update counter 's text
    counterElement.html((maxLength - this.value.length) + " chars left");
});

? live demo Here


Included below is a simple working JS/HTML implementation which updates the remaining characters properly when the input has been deleted.

Bootstrap and JQuery are required for the layout and functionality to match. (Tested on JQuery 2.1.1 as per the included code snippet).

Make sure you include the JS code such that it is loaded after the HTML. Message me if you have any questions.

Le Code:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  var len = 0;_x000D_
  var maxchar = 200;_x000D_
_x000D_
  $( '#my-input' ).keyup(function(){_x000D_
    len = this.value.length_x000D_
    if(len > maxchar){_x000D_
        return false;_x000D_
    }_x000D_
    else if (len > 0) {_x000D_
        $( "#remainingC" ).html( "Remaining characters: " +( maxchar - len ) );_x000D_
    }_x000D_
    else {_x000D_
        $( "#remainingC" ).html( "Remaining characters: " +( maxchar ) );_x000D_
    }_x000D_
  })_x000D_
});
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>_x000D_
_x000D_
<div class="row">_x000D_
  <div class="col-sm-6 form-group">_x000D_
    <label>Textarea</label>_x000D_
    <textarea placeholder="Enter the textarea input here.. (limited to 200 characters)" rows="3" class="form-control" name="my-name" id="my-input" maxlength="200"></textarea><span id='remainingC'></span>_x000D_
  </div>_x000D_
</div> <!--row-->
_x000D_
_x000D_
_x000D_


try this code in here...this is done using javascript onKeyUp() function...

<script>
function toCount(entrance,exit,text,characters) {  
var entranceObj=document.getElementById(entrance);  
var exitObj=document.getElementById(exit);  
var length=characters - entranceObj.value.length;  
if(length <= 0) {  
length=0;  
text='<span class="disable"> '+text+' <\/span>';  
entranceObj.value=entranceObj.value.substr(0,characters);  
}  
exitObj.innerHTML = text.replace("{CHAR}",length);  
}
</script>

textarea counter demo


Just register an Eventhandler on keydown events and check the length of the input field on that function and write it into a separate element.

See the demo.

var maxchar = 160;
var i = document.getElementById("textinput");
var c = document.getElementById("count");
c.innerHTML = maxchar;

i.addEventListener("keydown",count);

function count(e){
    var len =  i.value.length;
    if (len >= maxchar){
       e.preventDefault();
    } else{
       c.innerHTML = maxchar - len-1;   
    }
}
?

You should check the length on your server too, because Javascript might be disabled or the user wants to do something nasty on purpose.