Wednesday, November 3, 2010

Javascript to show how many characters are remaining to enter in textbox or textarea

<label for="mytextbox">Your Name : </label>
<input type="input" id="mytextbox" maxlength="20" onkeyup="javascript:countCharacters('mycounter',20,'mytextbox')">

<span id="mycounter">20</span>

And "onKeyUp" event of the textbox we are calling a javascript function "countCharacters()".

we will be writing a standard function which accepts only some parameters and rest of the processing will be done in the function.

To this function we have to pass 3 parameters
1) id of the span - where counter will be shown when user types something
2) max_chars - length of the textarea which we specified in maxlength="20"
3) myelement - the id of the textbox where user types text

The function is as below


//http://programming-in-php.blogspot.com/
function countCharacters(id,max_chars,myelement)
{
counter = document.getElementById(id);
field = document.getElementById(myelement).value;
field_length = field.length;
 if (field_length <= max_chars)  {   
// Here we Calculate remaining characters   
remaining_characters = max_chars-field_length; 
  // Now Update the counter on the page
   counter.innerHTML = remaining_characters;
  }
 } 

No comments:

Post a Comment