android.nick
android.nick

Reputation: 11217

Jquery Javascript make an if statement into a case statement not working

i'm using Jquery. This if-statement works:

if ($(this).siblings(".numOfMatchedKeywords").text() == 1) {
                    $(this).siblings(".numOfMatchedKeywords").css({'color':'#0099ff'})
               }

But when i tried to turn it into a switch case, I can't get it to work:

var numWord = $(this).siblings(".numOfMatchedKeywords").text();
                switch (numWord){
                    case 1: 
                        numWord.css({'color':'#0099ff'})
                    break;
                    case 2: 
                        numWord.css({'color':'#33cc33'})
                    break;
                    case 3: 
                        numWord.css({'color':'#ff0099'})
                    break;
                }

what am I doing wrong?

Upvotes: 2

Views: 1052

Answers (3)

morgar
morgar

Reputation: 2407

Compacted version:

var numWord = parseInt($(this).siblings(".numOfMatchedKeywords").text());
var colors = ['', '#0099ff', '#33cc33', '#ff0099'];
$(this).siblings(".numOfMatchedKeywords").css('color', colors[numWord]);

Upvotes: 2

Mark Coleman
Mark Coleman

Reputation: 40863

use parseInt()

parseInt($(this).siblings(".numOfMatchedKeywords").text(), 10);

Also, numWord is text and not a jQuery object.

var numWord = parseInt($(this).siblings(".numOfMatchedKeywords").text(), 10);
var $sib =$(this).siblings(".numOfMatchedKeywords");
switch (numWord) {
case 1:
    $sib.css({
        'color': '#0099ff'
    })
    break;
case 2:
    $sib.css({
        'color': '#33cc33'
    })
    break;
case 3:
    $sib.css({
        'color': '#ff0099'
    })
    break;
}

Upvotes: 3

Thomas Shields
Thomas Shields

Reputation: 8943

I'm guessing the if statement performs some auto-conversion on .text() and 1 and equates the string and the integer, whereas the switch statement does teh equivalent of ===. Not guaranteeing that above, but i'd recommend trying: 'case "1":instead ofcase 1:`

Also, you're applying your css to numWord which you set equal to the text of the element, not the element itself.

Upvotes: 0

Related Questions