Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count characters in field dynamically

I would like to count characters in a form textarea field dynamically, I know there is a similar question about this but I am wondering if it can count from a certain number towards 0, as example while writing a tweet on Twitter.

This code could be in javascript, PHP, it doesn't really matter to me.

like image 200
Deniz Zoeteman Avatar asked Nov 24 '25 12:11

Deniz Zoeteman


2 Answers

This should help you out. Here is a tutorial regarding usage - a demo is found below:

Usage:

<input name="text" onKeyDown="CountLeft(this.form.text, this.form.left,50);"
                   onKeyUp="CountLeft(this.form.text,this.form.left,50);">

Javascript:

<SCRIPT LANGUAGE="JavaScript">

 function CountLeft(field, count, max) 
 {
     if (field.value.length > max)
         field.value = field.value.substring(0, max);
     else
         count.value = max - field.value.length;
 }

</SCRIPT>

Demo - Credit to www.reconn.us

Hope this helps.

like image 155
Rion Williams Avatar answered Nov 26 '25 02:11

Rion Williams


With Javascript, use the KeyUp event handler, and check for the legnth-property on your text field on every event.

Example: http://jsfiddle.net/nslr/C2CNS/

like image 27
Thor Jacobsen Avatar answered Nov 26 '25 03:11

Thor Jacobsen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!