3

I am trying to select an input in my dom and I know it can be done like so:

$("input[value='foo']") 

...but lets say we have a variable x = 'foo'. How can I use that jquery selector with the variable. I tried:

query = "input[value=" + x + "]" 

but that results in "input[value=foo]" which is not the same.

How can I insert my variable into this jQuery selector?

1

2 Answers 2

3

You're close-- just missing those single-quotes:

query = "input[value='" + x + "']"; 

2020 Edit:

Four years later, and template literals enjoy support in every major browser except IE (which is on its way to deprecation). Furthermore, by leveraging a build process with tools like webpack and Babel, you can transpile them for backwards compatibility with IE. Thus, a more modern option like this is available:

query = `input[value='${x}']`; 
Sign up to request clarification or add additional context in comments.

4 Comments

I thought it would throw off the string with only a single single-quote
Thanks for the help
No problem! Glad to help!
Also, if you're not aware, single and double-quotes are functionally the same in Javascript, which is useful for when you need to do something like interpolate a value that needs to be wrapped in quotes. You may already know that, but hopefully it is useful for someone.
0
query = 'input[value="' + x + '"]'; 

wrap your variable in single quotes so the double quotes get added to the string.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.