JQuery Count Characters

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.

I am currently working on new features for this site, but I wanted to put something up. So today I am going to cover a simple little JQuery script that I installed in my blog entry system. Anyone with more than basic knowledge of JQuery can skip this one.

When creating my blogs I do a couple of things for SEO. One of those things is to ensure that my blog title is not longer than 70 characters. I dont make this a hard rule only a guideline. To save me having to count the characters manually or using a document editor like Word, I wrote a simple JQuery script to count the characters and apply some styling when I go over the character limit.

Step 1: Create a Display Container

In order to display the characters count, create a span next to the "Blog Title" input field and give it an id of "countChars".

<input type="text" name="blogTitle" id="blogTitle" /><span id="countChars"></span>

Step 2: Count the characters in the input field on keyup

The next step is a simple matter of adding a keyup listener to the blogTitle input which counts the number of characters and outputs it to the display container.

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

});
</script>
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