Michael Waxman
Michael Waxman

Reputation: 1825

jquery variable in selector

I want something like:

var user_name = $(".hidden_user_name").text();
$("a[name="+ user_name +"]").doStuff()...

This works:

$("a[name=joe123]").doStuff()...

EDIT:

The problem is clearly in that the user_name variable isn't set when the selector fires. How can I fix that?

Upvotes: 0

Views: 273

Answers (1)

user113716
user113716

Reputation: 322492

Your code should work. If you're not using some sort of asynchronous method of getting the value (like AJAX), then the second line won't execute until the first is complete.

What type of element is .hidden_user_name? If it is an <input> and you're trying to get the value of the input, you would do this instead:

var user_name = $(".hidden_user_name").val();

Or if there's more than one .hidden_user_name, you will only get the value of the first that is matched.

Try logging user_name before you utilize it to see if it is the value you expected.

console.log(user_name);

or

alert(user_name);

Upvotes: 1

Related Questions