1

Very quick and hopefully simple question.

I am trying to select a hidden input by value with some predefined variable.

var id = $("#puid").val();
$('input[value=id]').closest('tr').css({'background-color':'red'});

I thought the above code would have worked, however its not processing id as a variable. What is the right notation to do this? (I have tested the code by replacing id with the actual number and the rest of the code works fine).

2 Answers 2

5

remove it from the quotes, so the variable is concatenated into the string. They way you have it, it's looking for the literal value "id", and has no way of knowing that you're talking about a variable.

$('input[value='+id+']')

edit: more info - you could put double quotes around the id part, inside the strings, as in Nick's answer, which would make it safe to use with non-numeric ids. I omitted them since your example doesn't need them, as you said your ids are numeric.

Sign up to request clarification or add additional context in comments.

3 Comments

I'd use quotes at least here, since you don't know what that variable contains.
+1, but you should probably explain why he needs to do so, if he does not know that variables do not work inside strings.
Many thanks, problem solved. I shall embark upon much research involving concatenation and variables.
3

Concatenate the string selector with the variable, like this:

var id = $("#puid").val();
$('input[value="' + id + '"]').closest('tr').css({'background-color':'red'});

Currently, it's looking exactly for this: value="id", but you want your variable there.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.