I spit out this type of code frequently:
if ($(this).val() == 'X') {
$('#something').show();
}
else {
$('#something').hide();
}
I'm not crazy about having $('#something') appear twice. Is there a more elegant way of expressing this?
[Update] I phrased the question badly - I'm looking for a general solution, not just show/hide (and therefore toggle). For the general case of taking different actions on a selected element(s) based on a conditional, is there a more elegant construct?
toggle()
Toggle displaying each of the set of matched elements based upon the switch (true shows all elements, false hides all elements).
If the switch is true, toggle makes them hidden (using the hide method). If the switch is false, toggle makes them shown (using the show method).
var result = ($(this).val() != 'X');
$('#something').toggle(result);
or shorter
$('#something').toggle('X' != $(this).val());
for the general question of not having '#something' appear twice, I'd say it's more readable to have it twice. otherwise, you wind up with the following:
$('#something')[$(this).val()=='X'?'show':'hide']();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With