46

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?

ChristineS
  • 503
  • 1
  • 6
  • 12
  • 3
    Whats the question? Does that code not work? And if it doesn't, what does it do instead of what you expect? – Alex Wayne Oct 05 '12 at 08:44
  • @AlexWayne it only sets up the max limit of the text area which is 306. My Code doesn't work, and i need to set the limit to 160 only. – ChristineS Oct 05 '12 at 08:49
  • What server technology are you using? You should also consider server-side length validation, otherwise your approach can be bypassed if the user has JavaScript turned off in their browser. – Richard Ev Oct 05 '12 at 08:59
  • 1
    If you want a pure javascript solution and not jQuery check out my answer, i have a demo attached for you. – Christoph Oct 05 '12 at 09:07

10 Answers10

70

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)

Community
  • 1
  • 1
Nokia808Freak
  • 903
  • 9
  • 33
  • 6
    The keypress event is only fired when a key normally produces a character value. So you won't be able to catch backspace or paste actions. I'd recommend to use the input event instead -> https://developer.mozilla.org/en-US/docs/Web/Events/input – Felix Wienberg Nov 10 '15 at 18:09
  • 1
    consider using something like this to catch content changes as keyup won't handle all cases: #("message").bind('input propertychange', function () {textCounter(this,'counter',10);}) – vir us Apr 13 '18 at 18:47
40

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>
Anoop
  • 23,044
  • 10
  • 62
  • 76
9

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:

$(document).ready(function() {
  var len = 0;
  var maxchar = 200;

  $( '#my-input' ).keyup(function(){
    len = this.value.length
    if(len > maxchar){
        return false;
    }
    else if (len > 0) {
        $( "#remainingC" ).html( "Remaining characters: " +( maxchar - len ) );
    }
    else {
        $( "#remainingC" ).html( "Remaining characters: " +( maxchar ) );
    }
  })
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<div class="row">
  <div class="col-sm-6 form-group">
    <label>Textarea</label>
    <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>
  </div>
</div> <!--row-->
cjbrog
  • 786
  • 8
  • 10
5

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.

Christoph
  • 50,121
  • 21
  • 99
  • 128
  • I've tried it and it works well in JSfiddle. but when i combine it with my page it just wont show the Remaining Characters :( and by the way my language is C# – ChristineS Oct 05 '12 at 10:22
  • @Christine change the 306 in `onblur="textCounter(this,this.form.counter,306);"` to 160. and change the 160 in `field.value.substring(0, 160);` back to `maxlimit`. – Christoph Oct 05 '12 at 14:25
4

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');
        });
    });
1

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);
    });
});
Richard Ev
  • 52,939
  • 59
  • 191
  • 278
0

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!

Nokia808Freak
  • 903
  • 9
  • 33
0

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

Lucky
  • 16,787
  • 19
  • 117
  • 151
0

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

cnom
  • 3,071
  • 4
  • 30
  • 60
0

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);