Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count and display number of characters in a textbox using Javascript

Tags:

I am working on a project that requires me to count the number of characters entered in a text box and dynamically display the result elsewhere on the page.

As I said, this would preferably be done in jQuery or Javascript.

Thanks in advance.

like image 487
Kay Avatar asked Mar 19 '12 09:03

Kay


3 Answers

You could do this in jQuery (since you said you preferred it), assuming you want the character count displayed in a div with id="characters":

$('textarea').keyup(updateCount);
$('textarea').keydown(updateCount);

function updateCount() {
    var cs = $(this).val().length;
    $('#characters').text(cs);
}

UPDATE: jsFiddle (by Dreami)

UPDATE 2: Updating to include keydown for long presses.

like image 73
aurbano Avatar answered Sep 18 '22 17:09

aurbano


This is my preference:

<textarea></textarea>         
<span id="characters" style="color:#999;">400</span> <span style="color:#999;">left</span>

Then jquery block

$('textarea').keyup(updateCount);
$('textarea').keydown(updateCount);

function updateCount() {
var cs = [400- $(this).val().length];
$('#characters').text(cs);
}
like image 28
stkmedia Avatar answered Sep 19 '22 17:09

stkmedia


<script type="text/javascript">
function countChars(countfrom,displayto) {
  var len = document.getElementById(countfrom).value.length;
  document.getElementById(displayto).innerHTML = len;
}
</script>

<textarea id="data" cols="40" rows="5"
onkeyup="countChars('data','charcount');" onkeydown="countChars('data','charcount');" onmouseout="countChars('data','charcount');"></textarea><br>
<span id="charcount">0</span> characters entered.

Plain Javascript.

like image 38
Clyde Lobo Avatar answered Sep 20 '22 17:09

Clyde Lobo