html - Javascript If-else statement -


new javascript trying basic 'if, else' statement , can't work...

$(function () {     if ($('.feature:contains("firmness rating 1")')) {     $('#firm').css({'background-image': 'url(firmness1.png)'}).text('firmness rating 1');     }     if ($('.feature:contains("firmness rating 2")')) {     $('#firm').css({'background-image': 'url(firmness2.png)'}).text('firmness rating 2');     }     if ($('.feature:contains("firmness rating 3")')) {     $('#firm').css({'background-image': 'url(firmness3.png)'}).text('firmness rating 3');     }     if ($('.feature:contains("firmness rating 4")')) {     $('#firm').css({'background-image': 'url(firmness4.png)'}).text('firmness rating 4');     }     if ($('.feature:contains("firmness rating 5")')) {     $('#firm').css({'background-image': 'url(firmness5.png)'}).text('firmness rating 5');     }     else {     $('#firm').css({'background-image': 'url(firmness1to5.png)'}).text('choose perfect firmness');  }  }); 

i know there must bette way this, please :)

thanks

p

try

$(function () {     if ($('.feature:contains("firmness rating 1")').length) {         $('#firm').css({'background-image': 'url(firmness1.png)'}).text('firmness rating 1');     }     else if ($('.feature:contains("firmness rating 2")').length) {         $('#firm').css({'background-image': 'url(firmness2.png)'}).text('firmness rating 2');     }     else if ($('.feature:contains("firmness rating 3")').length) {         $('#firm').css({'background-image': 'url(firmness3.png)'}).text('firmness rating 3');     }     else if ($('.feature:contains("firmness rating 4")').length) {         $('#firm').css({'background-image': 'url(firmness4.png)'}).text('firmness rating 4');     }     else if ($('.feature:contains("firmness rating 5")').length) {         $('#firm').css({'background-image': 'url(firmness5.png)'}).text('firmness rating 5');     }     else {         $('#firm').css({'background-image': 'url(firmness1to5.png)'}).text('choose perfect firmness');     }  }); 

if want many if statements chained, use else if.

also, check if jquery selector able select elements, use $(selector).length, returns number of matched elements. if(number) returns true positive value , false 0 or negative. so, if selector matches elements, if($(selector).length) returns true.


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - Bypass Geo Redirect for specific directories -

php - .htaccess mod_rewrite for dynamic url which has domain names -