Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: More elegant if/else with selectors

Tags:

jquery

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?

like image 920
Parand Avatar asked Dec 14 '22 04:12

Parand


2 Answers

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());
like image 100
Georg Schölly Avatar answered Jan 21 '23 03:01

Georg Schölly


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']();
like image 24
Jimmy Avatar answered Jan 21 '23 05:01

Jimmy