views:

744

answers:

4

I have been trying to find out why the following lines of code do not work:

$('#add-cloud > select').change(function() {

 var selected = parseInt($('#add-cloud select option:selected').val()); 

 $("#cloud-calculator table tr:eq(selected)").css("color", "red");

});

If I change :eq(selected) to :eq(4) for example - works fine. How do you pass variable as an argument to :eq() ?

+2  A: 

You have to concatenate your variable with your selector:

$("tr:eq("+selected+")");
Jonathan Sampson
The code is right, but the description of what's going on with it is very wrong.
chaos
Thank you! I tried it it single quotes before and it didn't work. I guess I wasn't paying attention to the double quotes.
dalizard
Right, single quotes didn't work because what you're doing isn't 'escaping' anything, it's terminating the first string "tr:eq(", adding the selected variable, and then adding another string ")".
chaos
Thank you Chaos too :)
dalizard
Sorry, didn't mean "escape" in that sense. Concatenate would be less misleading.
Jonathan Sampson
+1  A: 

The way you're doing it, you're embedding the actual string "selected" in the selector. You need to construct a string using your selected variable as a part of it:

$("#cloud-calculator table tr:eq(" + selected + ")").css("color", "red");
chaos
+1  A: 

Also, you can simply use the 'this' object to get the seleted value.

$('#add-cloud > select').change(function() 
{
    var rowSelector = '#cloud-calculator table tr:eq(' + parseInt(this.val()) + ')';
    $(rowSelector).css("color", "red");
}
SolutionYogi
A: 

Wow! Thanks to all especially "Jonathan Sampson"

Elumalai Jayamaran

jelumalai