Textarea char counter, a jQuery plugin

Some weeks ago I received a customer request to add a character counter to a textarea field and I made it using “classic” Javascript. Now that I’m learning jQuery and have some spare time, I tryed to transform my custom function to a jQuery plugin.

This is my first attempt to build a jQuery plugin and maybe there’s already another plugin that does the same thing but it have been a really nice exercise.

This plugin will give you the method setCounter([maxLength]). If you call it on a textarea field you will get a counter that gets updated every time the user write a character.

The maxLength parameter is not mandatory so if it’s undefined you will get a simple character counter like this:

<div id="textareaId_counter">
  <span class="length">27</span>

while if you pass an integer to the method the user won’t be able to write a number of character greater than maxLength and you will get a counter like this:

<div id="textareaId_counter">
  <span class="length">27</span>
  <span class="sep">/</span>
  <span class="maxLength">500</span>

This is the code. Save it in a text file named something like jquery.textareaCharacterCounter.js and include it in your page:

jQuery.fn.setCounter = function(maxLength){
  return this.each(function(){
    var jqthis = jQuery(this);
    if (jqthis.is('textarea')){
      var counterId = jqthis.attr('id') + "_counter";
      var htmlCounter = '<div id="' + counterId + '">';
      htmlCounter += '<span class="length">' + jqthis.val().length + '</span>';
      if (maxLength){
        htmlCounter += '<span class="sep">/</span>';
        htmlCounter += '<span class="maxLength">' + maxLength + '</span>';
      htmlCounter += '</div>';
        var content = jqthis.val();
        if (maxLength && content.length > maxLength){
          content = content.substring(0,maxLength)
          jqthis.val( content );
        jQuery('#' + counterId + " > span.length").text(content.length);        
    } else {
      alert("Not applicable to element: " + jqthis);

How to use it

// Add a simple counter

// Add a counter and set maximum length to 500 characters

Better fonts for Lotus Notes 8.5 in Ubuntu

I’ve just installed Lotus Notes 8.5 on Ubuntu and the first thing I noticed was the horrible fonts used in the interface. I’ve searched for a setting, but couldn’t find none so Goggle helped me: Notes is looking for a font called Luxi contained in the package ttf-xfree86-nonfree.

Installation is very simple:

sudo apt-get install ttf-xfree86-nonfree

Insert your password and you are done.

Scriptlet and JSTL variable sharing

I know that mixing scriplets and JSTL in JSP is a bad practice, but sometimes you can’t avoid it and every time I do it I can’t remember how to share variables between scriplets and JSTL so this post is a sort of reminder for the future. Hope it can be useful for other forgetful persons like me :-)

Access scriptlet variable with JSTL

String myVariable = "Test";
pageContext.setAttribute("myVariable", myVariable);

<c:out value="myVariable"/>

Access JSTL variable with scriptlet

<c:set var="myVariable" value="Test"/>

String myVariable = (String)pageContext.getAttribute("myVariable");

Selective Javascript Loader 1.1

I’ve just update the Selective Javascript Loader plugin with some bugfixes and improvements:

  • Added the option to choose if Javascript files should be included in the header or in the footer of the page. This option is available only if you are using WordPress 2.8 and above
  • Added WordPress version checking.
  • Corrected script inclusion for Wordpress 2.7
  • Some code optimization
  • Corrected a layout bug in the settings page

Read more or download it.

Selective Javascript Loader

I’ve just released Selective Javascript Loader my first WordPress plugin. It’s a very simple plugin that automatically loads different Javascript files based on the blog section that is being viewed (index, category, single post, page).

It can be really useful if you make extensive use of Javascript in your theme and want to split the code and load functions only when you need them.

Check it out!

Check date validity with Javascript

A simple JavaScript function to check date validity

function checkDateValidity(day, month, year){

  month = month - 1;
  var message = '';

  var date = new Date(year,month,day);

  if (year != date.getFullYear())
    message = 'Year not valid';

  if (month != date.getMonth())
    message = 'Month not valid';

  if (day != date.getDate())
    message = 'Day not valid';

  return message;

Speed up Firefox awesome bar

Using the new Firefox awesome bar could result in a frustrating experience, because the SQLite database that holds all the data used by Firefox can get heavily defragmented.

You can get an huge speed improvement running this command inside the Firefox error console:


Put the command above in the code field (in a single line) and press the evaluate button.

Single post template based on category #2

In my previous post I talked about a Lorelle blog post on creating single post templates for different tags.

After using the code snippets “as is” I tryed to build a more flexible solution so I’ve come up with this little function:

function getSingleTemplate(){
  $category = get_the_category();
  $templateName = TEMPLATEPATH . '/single_' . $category[0]-&gt;category_nicename .'.php';
  if (!file_exists($templateName)){
    $templateName = TEMPLATEPATH . '/single_default.php';
  return $templateName;

This function must be called inside the single.php template: it gets the first post’s category, searches for a template named like single__post_first_category_slug_.php and returns its path; if the file doesn’t exists it will return the single_default.php template path.

Single post template based on category

Today, while trying to customize the single.php template for a specific category I found a pretty old article written by Lorelle:

Creating Multiple Single Posts for Different tags.

Her tip is really simple and really useful: just rename your single.php to single1.php and create a new single2.php with your category specific layout; after that, create a new single.php file with this code:

$post = $wp_query->post;
if ( in_category('1') ) {
  include(TEMPLATEPATH . '/single2.php');
} else {
  include(TEMPLATEPATH . '/single1.php');

So, if the post is in category 1 WordPress will use the single2.php otherwise it will use single1.php.


I wrote a more flexible solution: check it out.

Add a category filter to WordPress search

WordPress has a simple function to build a search form for your blog and in this tutorial I’ll show you how to add a category filter to it.

<?php get_search_form(); ?>

This function will look for a file called searchform.php inside your template folder: if it doesn’t exist it will output the standard search form. So, if it isn’t already in place, create your custom searchform.php and copy into it the default search form output. It should look similar to this:

<form role="search" method="get" id="searchform" action="<?php bloginfo('siteurl'); ?>">
    <label class="screen-reader-text" for="s">Search for:</label>
    <input type="text" value="" name="s" id="s" />
    <input type="submit" id="searchsubmit" value="Search" />

We want to add a select box to let the user search in a specific category or in all tags: to achive this we’ll use another default WordPress function.

The wp_dropdown_tags function will build for you a select box with all your tags. Take a look at the documentation for all the available options.

<?php wp_dropdown_tags( 'show_option_all=All tags' ); ?>
<!-- This is a sample output of the function -->

<select name='cat' id='cat' class='postform' >
  <option value='0' selected='selected'>All tags</option>
  <option class="level-0" value="1">Uncategorized</option>
  <option class="level-0" value="3">HTML &amp; CSS</option>
  <option class="level-0" value="4">Java</option>
  <option class="level-0" value="5">Links</option>
  <option class="level-0" value="6">Linux</option>
  <option class="level-0" value="9">Javascript</option>
  <option class="level-0" value="32">XML</option>

Now add the category select box to the form modifying your searchform.php like this:

<form role="search" method="get" id="searchform" action="<?php bloginfo('siteurl'); ?>">
    <label class="screen-reader-text" for="s">Search for:</label>
    <input type="text" value="" name="s" id="s" /> 
    in <?php wp_dropdown_tags( 'show_option_all=All tags' ); ?> 
    <input type="submit" id="searchsubmit" value="Search" />

That’s it. It just works out of the box.

A finishing touch

Now that you have a nice category filter in your search form it would be great to modify the search result page and add something like Search result for “foo” in category “bar”. Well, it’s quite easy: we need do add a simple function to the function.php file. Remember that every function in this file will be automatically available in your theme.

This is a simple function that gets the cat parameter from the request and if it’s not null it searches the category name. It has two input parameters so you can pass two strings to be displayed before and after the category name. If cat is null or empty or “0” (All tags) it will return an empty string.

function getCatSearchFilter($pre,$post){
  $category = "";
  $catId = htmlspecialchars($_GET["cat"]);

  if ($catId != null && $catId != '' && $catId != '0'){
    $category = $pre.get_cat_name($catId).$post;

  return $category;


Now open you search.php, add the function call to the page and you are done:

<h1>Search Results for <?php echo(get_search_query());?><?php echo(getCatSearchFilter(' in category ',''));?></h1>

Update 31.12.2011

Finally I wrote a blog post on adding a Multiple tags filter in WordPress search. Check it out!