JQuery Count Characters - page 2

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.

At this stage we have our character count, but it would be nice if there was a visual way of alerting the user (ie me) to when the character limit has exceeded the desired length.

Step 3: Apply styling to countChars span depending on character count

We could use an alert box as a simple way of warning us when we enter too many characters but I find that to be too much of an interupt to my work flow, especially as I may actually want to enter a longer title than normal. Instead I favour changing the background colour of the character count to a primary colour such as red when the limit it exceeded. JQuery makes this really simple.

Lets create two style class's for the span. The first will be for when the character count is less than or equal to 70, and the second for counts above 70.

.countCharsOk {
color:#000;      
padding:0 10px 0 10px;
}

.countCharsRed {
color:#fff;
background-color:red;
padding:0 10px 0 10px;
}

To apply the relevent css class's modify the script as follows.

<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 70
if(charLength > 70) {
//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');
}
});
});
</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