Davide recently posted an article entitled Simple pluralization with jQuery.
Now while the whole premise is fairly easy to grasp (changing the pluralisation of words depending on user input), and his code works, separating the function from the event handler, I just thought that those who are a bit more confident with jQuery or JavaScript in general would find it a bit cumbersome to do a very simple job.
Here’s what I would do:
<label for="interval">Time since you last birthday:</label> <input id="interval" name="interval" size="2" value="" /> <span id="interval-desc">days</span>
Nothing tricky there – a label, input and span element.
jQuery(function($) {
$("#interval").blur(function() {
$("#interval-desc").text(($(this).val() == 1) ? "day" : "days");
});
});
Obviously you need to make sure to include the jQuery library. When the DOM has loaded and is ready to be manipulated, then we want the check to happen when the focus has left the input field (blur).
Davide has his code doing the check on the keypress, but I dislike this for several reason. Firstly, this calls the check on all keypresses, when actually after the first keypress, we would already know whether the contents were just a 1 or not. Secondly, entering a number like 12, would mean the display changes from days to day, then back again. This maybe distracting to the user, and as the actual description shown is not critical to future inputs, there’s no reason to change it until the user has finished entering their numbers.
The actual check is relatively simple, but looks confusing due to using the JavaScript tertiary operator, instead of If…Else code block that you may be more familiar too. It simply sets the text value of the element with ID interval-desc to either day, or days, depending if the value of input box is 1 or not.
All this is not to say Davide’s version is wrong – indeed, in more complicated scripts, unhooking the functionality away from the HTML elements and the event handler is definitely a good thing. In this case though, the above is succinct enough that having to repeat it on another page is not going to be the end of the world.