JQuery Count Characters - page 3

Author: Steven Neiland
Published:

Warning: This blog entry was written two or more years ago. Therefore, it may contain broken links, out-dated or misleading content, or information that is just plain wrong. Please read on with caution.

Step 4: Run the script on initial form load

At this stage the script is working perfectly apply and removing the css class's and updating the character count. Only one thing remains and that is to run the script on initial page load. This is necessary if we are editing an existing post and want to see the character count when the form loads. We could do this part server side but it is not necessary, all we need to do is call the keyup event once when the form is finished loading.

<script type="text/javascript">
$(document).ready(function(){
//every time user types in the blogTitle input field do the following
$('#blogTitle').keyup(function() {

//get the length of the input text value
var charLength = $(this).val().length;

//set the inner html of chountChars equal to charLength
$('#countChars').html(charLength);

//if charLength gt 60
if(charLength > 60) {
//remove all existing css class's from countChars
//then add the class 'countCharsRed'
$('#countChars').removeClass().addClass('countCharsRed');
} else {
//remove all existing css class's from countChars
//then add the class 'countCharsOk'
       $('#countChars').removeClass().addClass('countCharsOk');
}
});

//Call keyup event once immediately after the form loads
$('#blogTitle').keyup();
});
</script>

So there you have it, a simple script to count the characters in an input box and give us a visual alert when.

1 2 3

Reader Comments

  • Please keep comments on-topic.
  • Please do not post unrelated questions or large chunks of code.
  • Please do not engage in flaming/abusive behaviour.
  • Comments that contain advertisments or appear to be created for the purpose of link building, will not be published.

Archives Blog Listing