RSS feed

Nutsmuggling

Simple pluralization with jQuery

Don’t you hate it when a html form shows something like this?

test-blog-add-new-wordpress-1.png

I understand we’re in a territory that most people would label as “cosmetics”, but I was taught better than this, and the idea of writing “1 days” still makes my stomach ache.

The most obvious solution is to follow the traditional paper forms convention and write something like “day/days”, but can we really stop automation?

So here’s my solution. It’s a simple one, based on the wonderful library that is jQuery.

First, add a couple of spans after your input, one for singular, one for plural.

<input id="interval" name='interval' size='2' value=''></input> 
<span class='interval-desc' id="interval-singular">day</span>
<span class='interval-desc' id="interval-plural">days</span>

Then, put this script somewhere in your <head>:

// Make sure the src attribute points to
// the actual location of jQuery
<script type="text/javascript" src="jquery.js"></script> 
<script type="text/javascript">
//<![CDATA[     
$j=jQuery.noConflict(); 
 
function updateIntervalDescriptor () { 
   $j(".interval-desc").hide();
   var number = "-plural";
   if ($j('input#recurrence-interval').val() == 1 
     || $j('input#recurrence-interval').val() == "")
       number = "-singular"
var descriptor = "span#interval-" + number;
   $j(descriptor).show();
}     
 
$j(document).ready( function() {
   updateIntervalDescriptor(); 
   $j('input#recurrence-interval').keyup(updateIntervalDescriptor);
}
//]]>
</script>

The concept is pretty straighforward. If your input contains a value bigger than 1, or no value, the “day” span is shown, otherwise the “days” span is shown. It’s really a no-brainer, but I thought I’d share it, for the love of grammar :)

Of course you can use the same rationale to make your forms more dynamic. The original script behind this post changes the text according to frequency, so you have day/s, week/s and month/s. Once you grasp the basics it’s pretty easy to automate your forms this way.

As a side note, you may have noted this line:

$j=jQuery.noConflict();

This is to stay on the safe side and avoid potential conflict with other libraries. In my case, I acquired this habit after starting coding wordpress plugin; Wordpress, at least up to 2.5, uses both Prototype and jQuery; both libraries use the $ selector.

Update

Gary Jones suggests an even simpler way to pluralize through jQuery.
I do favour myself his method, which is more synthetic than mine.

My example was actually born stripping heavily from production code. For the sake of focusing, I decided to take out most of the context. In the original code, part of Events Manager 2.0, I don’t use “day” but a localised string, introduced through

_e('day', 'dbem');

I prefer not to mingle javascript and PHP when not strictly necessary. Moreover, the string displayed depends also on a frequency selector, so I have also ‘weeks’ and ‘months’, and a more complicated id structure. That is why I went for a longer approach and more spans. If your needs aren’t that complicated, go with Gary’s tip.

Lovedeity has also a point reminding me that many languages have more complicated rules for plural. When I find a French localiser, I’ll have to look into this.

Thank ye all folks, we’re having a nice discussion here!

Share and Enjoy:
  • Digg
  • del.icio.us
  • Google
  • Technorati
  • StumbleUpon
  • Furl
  • Reddit

30 responses to “Simple pluralization with jQuery”

  1. Lovedeity says:

    For English, that’s an appropriate mechanism. Once you go beyond that, it gets a lot more difficult. For example, French has a zero value with a singular designation (zero day). Russian has three forms for pluralization based on some complicated rules.

    …just something to consider if you ever decide to internationalize.

    I found this to be an excellent resource for pluralization:

    https://developer.mozilla.org/en/Localization_and_Plurals

  2. Jose says:

    Didn’t remember you can use noClonflict() to change the selector to what you want.. maybe i try to get used to taht from now on :)

  3. Davide says:

    @lovedeity
    You’re right there. Actually I meant to put a footnote about those languages with the dual number and so on, but I forgot in the process. Good point, and thanks for sharing the resource.

    @Jose The noConflict() method comes in really handy especially when you’re dealing with other people’s frameworks, that is, you never know what might be in it. In my case i was forced to use it after realising that Prototype had already taken possessiojn of $.

  4. Gary says:

    Hi Davide,

    While your version works and everything, I can’t help but feel it’s a bit clunky for such a simple task. I’ve written up my thoughts at http://garyjones.co.uk/blog/pluralization/ . Regards, Gary.

  5. Davide says:

    Good tip, I updated the post to acknowledge it. As far as the blur() suggestion goes, i had also used it at first, but I guess I prefer more responsiveness, so I went with keyup().

  6. Gary says:

    Hat tip appreciated, thanks :) The “Gary’s tip” link in the update is almost certainly pointing to the wrong URL.

  7. Davide says:

    Fixed that :)

  8. Gary says:

    Hi Davide,

    I’m getting some odd 404’s to my site from links in the post and comment of this page.

    I think it’s the Google Analytics plugin (or another) which, when adding the rel=”nofollow” is using the wrong (single) quotes – check the source of this page and you’ll see. The browser (Firefox at least) interprets the invalid code correctly, but the Analytics doesn’t giving me 404s recorded like http://garyjones.co.uk/‘%20rel=’external%20nofollow . Any chance you could fix these up?

    Thanks (and feel free to delete this comment – I couldn’t find a contact form for you!)

    Gary.

  9. Even Simpler Pluralization with jQuery — Gary's Code says:

    [...] Davide recently posted an article entitled Simple pluralization with jQuery. [...]

  10. brad says:

    excelent blog good info congrats. To get the best frostwire download click on the link

  11. Dewitt Zito says:

    What youre saying is completely correct. I realize that everybody should say the identical issue, but I just feel that you place it inside a way that everyone can understand. I also really like the images you put in here. They suit so properly with what youre wanting to say. Im certain youll get to so many individuals with what youve acquired to say.

  12. dell streak review says:

    one of my friend advice me to visit this site, and this is the information that I looking for.

  13. South Realty says:

    Does your website effectively exhibit emoticons? Since my site cannot?-

  14. dermabrazja says:

    Interesting post made here. One thing I would really like to say is always that most professional career fields consider the Bachelor’s Degree like thejust like the entry level requirement for an online college degree. Although Associate Degrees are a great way to start out, completing a person’s Bachelors opens up many doors to various employment opportunities, there are numerous internet Bachelor Diploma Programs available from institutions like The University of Phoenix, Intercontinental University Online and Kaplan. Another concern is that many brick and mortar institutions offer Online types of their qualifications but generally for a substantially higher payment than the corporations that specialize in online education plans.

  15. LaRue Tactical says:

    I understand where your coming from, and I totally love the post. It goes without saying I also love the design of your website, incredibly resourceful. Bye for now.

  16. Przysnobor says:

    What an intriguing post, hold posting better half

  17. Lyrics SNUQ says:

    Many hours I’ve been searching for the notes about it. Eventually, I found the answer – hidden within your article. Well, thank you and good luck!

  18. coach online says:

    Time to oust all commies from government.

  19. longlox hair extensions says:

    hey this siteis excelent,i post here regular and find comments are helping me with my site also

  20. Wow, I didn’t realize AP is branching out… – (10 Replies) | wow nice watches! says:

    [...] uhr panerai uhren panerai uhren herren panerai uhrenarmband panerai watch panerai watch bands panerai watches This entry was posted in Uncategorized by admin. Bookmark the [...]

  21. Kenzing says:

    quality post…

    john lewis ugg boots love, http://www.melisinema.com ,thanks ugg…

  22. Kaliummentes so says:

    I feel that may be a captivating aspect, it made me assume a bit. Thank you for sparking my pondering cap. From time to time I get such a lot in a rut that I simply feel like a record.

  23. Britt Robertson says:

    Very good solution to a common problem, as the one comment suggested it would get sticky with multiple languages but with just English it is brilliant.

  24. Hildred Guarriello says:

    I got so bored at the moment afternoon, but when I watched this YouTube funny clip at this weblog I turn into fresh and cheerful as well.

  25. Jessie Alesci says:

    My spouse and i got very lucky Emmanuel managed to do his analysis through the ideas he got out of the site. It is now and again perplexing just to continually be offering information and facts which the rest could have been trying to sell. We really know we now have the website owner to be grateful to for this. The specific explanations you’ve made, the straightforward website menu, the friendships you assist to foster – it’s got all wonderful, and it’s facilitating our son in addition to the family reckon that this theme is amusing, and that’s extraordinarily fundamental. Thank you for all!

  26. visit says:

    Great post. I was checking continuously this blog and I’m impressed! Very useful information particularly the last part :) I care for such information a lot. I was looking for this particular info for a long time. Thank you and best of luck.

  27. short term disability insurance carlsbad says:

    hello there and thank you for your info – I’ve certainly picked up anything new from right here. I did however expertise several technical points using this website, since I experienced to reload the web site many times previous to I could get it to load properly. I had been wondering if your web host is OK? Not that I’m complaining, but slow loading instances times will very frequently affect your placement in google and can damage your high-quality score if advertising and marketing with Adwords. Well I am adding this RSS to my email and could look out for a lot more of your respective fascinating content. Make sure you update this again soon..

  28. Conception Fringuello says:

    I am constantly looking online for tips that can facilitate me. Thank you!

  29. Jonathon Pownell says:

    I truly liked your own article article.

  30. pregnancy versus period symptoms says:

    I in addition to my pals happened to be looking through the excellent strategies located on your web blog then the sudden came up with a terrible feeling I had not thanked the web site owner for those tips. All of the young boys had been as a consequence happy to see all of them and already have sincerely been enjoying these things. Thanks for actually being very considerate and for obtaining this form of remarkable issues most people are really desperate to know about. My very own honest apologies for not saying thanks to you sooner.

Leave a Reply