Simone Melloni
Simone Melloni

Reputation: 430

Jquery shorthand IF-ELSE

i need to do a shorthand IF-ELSE with JQuery. My code:

    $('#somediv').val() != 0 ? $('#somediv').toggleClass('class1') : $('#somediv').toggleClass('class2');

Simple code, but doesn't work. Some help please? Thanks in advance

EDIT: this work:

if ($('#somediv').val() != 0) {
    $('#somediv').toggleClass('class1');
}else{
    $('#somediv').toggleClass('class2');
}

But the shorthand doesn't...Ty for the patience

Upvotes: 2

Views: 2396

Answers (2)

tokyovariable
tokyovariable

Reputation: 1656

You want to use text() to get the value of the div, that's if it's not an input. If you provide what #somediv looks like that will help.

 $('#somediv').text() != 0 ? $('#somediv').toggleClass('class1') : $('#somediv').toggleClass('class2');

The shorthand "if-else" is called ternary and can be used with vanilla javascript

Upvotes: 0

Claudio Redi
Claudio Redi

Reputation: 68400

If somediv is actually a div as the name would indicates, you should use text() or html() instead of val() since value is only valid for input elements.

Upvotes: 3

Related Questions