article

Sunday, August 11, 2013

Jquery Count Remaining Character

Jquery Count Remaining Character

 
<script type="text/javascript" src="js/jquery-1.9.0.min.js"></script><script>
$(document).ready(function(){
 var totalChars   = 100; //Total characters allowed in textarea
 var countTextBox  = $('#counttextarea') // Textarea input box
 var charsCountEl  = $('#countchars'); // Remaining chars count will be displayed here
 charsCountEl.text(totalChars); //initial value of countchars element
 countTextBox.keyup(function() { //user releases a key on the keyboard
  var thisChars = this.value.replace(/{.*}/g, '').length; //get chars count in textarea
  var per = thisChars*100; 
  var value= (per / totalChars); // total percent complete
  if(thisChars > totalChars) //if we have more chars than it should be
  {
   var CharsToDel = (thisChars-totalChars); // total extra chars to delete
   this.value = this.value.substring(0,this.value.length-CharsToDel); //remove excess chars from textarea
  }else{
   charsCountEl.text( totalChars - thisChars ); //count remaining chars
   $('#percent').text(value +'%');
  }
 }); 
});
</script>

<div class="main-item"><div><textarea name="counttextarea" id="counttextarea" cols="45" rows="5" style="width: 400px;padding: 10px;"></textarea></div>
<div><span name="countchars" id="countchars"></span> Characters Remaining. <span name="percent" id="percent"></span></div>
</div>

Related Post