views:

127

answers:

2

I want to add 'Year' or Years' to the end of a string depending on the string. Like this:

$("#selector").val(conditional_value_here);

Using jQuery UI I have a slider that manipulates a value:

$("#slider").slider({
    value: 1,
    min: 1,
    max: 25,
    step: 1,
    slide: function(event, ui) {
        $("#amount").val(ui.value + ' Year' + function(){return (ui.value == 1) ? '' : 's';} );
    }
  });

// and again I want to do the same for the initialization of the value:
$("#amount_3").val($("#slider_3").slider("value") + ' Jahr' + function(){return ($("#slider_3").slider("value") == 1) ? '' : 's';});

This does not work. What is the correct way to to this?

A: 

just

$("#amount").val(ui.value + ' Year' + (ui.value == 1) ? '' : 's');
Reigel
don't forget precedence. `ui.value + ' Year' + (ui.value == 1)` will always be true.
nickf
+1  A: 

As Reigel said, you can just use the ternary operator ? : without requiring the function.

condition ? x : y;

If condition is true, then x is returned, otherwise y is returned. When using it, just make sure to use parentheses liberally.

str = "This is " + numDays + numDays == 1 ? " day" : " days" + " old";

// no matter the value of numDays, the above always evaluates to " day"
// it is equivalent to:

str = ("This is " + numDays + numDays == 1) ? (" day") : (" days" + " old");

// instead, this is probably what was wanted:

str = "This is " + numDays + (numDays == 1 ? " day" : " days") + " old";

Alternatively, if you had a really really really good reason to do something like what you tried in your example, you could make it work like this:

$("#amount").val(
    ui.value + ' Year' + (function(){return (ui.value == 1) ? '' : 's';})()
);

...but if I saw something like that in production, I'd be forced to hunt you down with a large axe.

nickf
thanks, but could you explain how does this work: str = "This is " + numDays + (numDays ? " day" : " days") + " old";I mean, where's the condition? Since there is no comparative operator involved will the var numDays not evaluate to TRUE unless it's zero? so that both 1 and 3 will result in the strings '1 days' and '3 days' respectively?
mikkelbreum
@mikkelbreum ah true -- pardon my brainmelt. i'll edit now.
nickf