ChristineS
ChristineS

Reputation: 513

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?

Upvotes: 47

Views: 143624

Answers (10)

Anoop
Anoop

Reputation: 23208

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>

Upvotes: 40

Nokia808Freak
Nokia808Freak

Reputation: 921

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)

Upvotes: 72

Manjunath Akalawadi
Manjunath Akalawadi

Reputation: 395

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

Upvotes: 4

cjbrog
cjbrog

Reputation: 786

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

Upvotes: 9

Gleb Umarov
Gleb Umarov

Reputation: 35

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

Upvotes: 0

cnom
cnom

Reputation: 3241

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

Upvotes: 0

Lucky
Lucky

Reputation: 17345

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

Upvotes: 0

Nokia808Freak
Nokia808Freak

Reputation: 921

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!

Upvotes: 0

Christoph
Christoph

Reputation: 51191

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.

Upvotes: 5

Richard Ev
Richard Ev

Reputation: 54097

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

Upvotes: 1

Related Questions