3

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'}); } 
3
  • 1
    What's #clicked_info? Are you sure it contains either 1 or 2? Commented Jan 17, 2013 at 2:54
  • This could use some more context. For instance, are you expecting the CSS to be applied when the value changes or just on page load? You're getting answers about string vs. number comparisons which can make it fail (so using parseInt() is a good practice), but it could just as well succeed and you might be seeing some other problem. Commented Jan 17, 2013 at 3:17
  • Is it an <input>, or something else? A wild guess: if you're trying to get the text content, use .text(), not .val(). Commented Jan 17, 2013 at 3:17

3 Answers 3

2

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'){ 
Sign up to request clarification or add additional context in comments.

3 Comments

I might add here that if you're converting the string to integer, then might as well as the === comparison operator instead of ==.
I think javascript already doing that, when you compare '1' == 1 it return false. You don't need to write '1' === 1
Yaah, it will process 1 == '1' :)
1

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); 

1 Comment

1 == '1'. This shouldn't matter.
0

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) 

1 Comment

Not only will you get unexpected results if your string beings with 0x (hexadecimal), you'll also get unexpected results if your string begins with 0 (octal), which is far more common than 0x.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.