Saturday, 3 December 2011

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


Today we will be seeing a javascript which will help us to show how many characters are remaining for a textbox or textarea,As soon as the user starts typing in a textbox or textarea, then we will show how many characters are remaining for entering into the textbox.

Here we are creating a simple textbox, and we are specifying the "maxlength" of the textbox to 20.

<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 parameters1) id of the span - where counter will be shown when user types something2) 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

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

Now you can use this function anywhere, without a need to modify this function.

The full code to try out is here

<script type="text/javascript"> 
function countCharacters(id,max_chars,myelement) 
counter = document.getElementById(id); 
field = document.getElementById(myelement).value; 
fieldfield_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;  } 
 } </script> 
 
<label for="mytextbox">Your Name : </label> 
<input type="input" id="mytextbox" maxlength="20" onkeyup="javascript:countCharacters('mycounter',20,'mytextbox')"> <span id="mycounter">20</span> 

No comments:

Post a Comment

Visual comparison of the two methods, creating a simple table.

Option 1, using PHP: // PHP $html = '<table>' ;     foreach ( $data as $row ) {     $html .= '<tr>...