Ali Tua
Ali Tua

Reputation: 33

Change color depending on value

I don't why this is not working. Can somebody tell me what is the problem with this?

var x = $('#clicked_info').val();

if(x == 1) {

    $('#companyname_ph').css({'color':'yellow'});

}

else if(x == 2) {

    $('#companyname_ph').css({'color':'red'});

}

Upvotes: 3

Views: 243

Answers (3)

Andbdrew
Andbdrew

Reputation: 11895

like the other folks here have noted, you should use parseInt when you want to convert a string representation of an integer to a number type. I would add that you should provide a radix to parseInt because if you don't, you may get unexpected results if your string starts unexpectedly with "0x" :)

try doing:

var x = parseInt($('#clicked_info').val(), 10)

Upvotes: 0

Sahal
Sahal

Reputation: 4136

You need to use parseInt to convert a string to an integer.

var x = $('#clicked_info').val();

if(parseInt(x) == 1){

   $('#companyname_ph').css({'color':'yellow'});

} else if(parseInt(x) == 2){

    $('#companyname_ph').css({'color':'red'});

}

OR use string comparison

if(x == '1'){

Upvotes: 2

Ricardo Lohmann
Ricardo Lohmann

Reputation: 26320

val returns a string

x == 1 shoulb be x == '1'

x == 2 should be x == '2'

Or you can convert x to int using the following.

var x = $('#clicked_info').val();
x = parseInt(x);

Upvotes: 1

Related Questions