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?

Jeremy Thomas
  • 6,240
  • 9
  • 47
  • 92
  • `$("input[value='" + x + "']");` - Possible duplicate of [How to use javascript variables in jquery selectors](http://stackoverflow.com/questions/5891840/how-to-use-javascript-variables-in-jquery-selectors) – Tyler Roper Oct 19 '16 at 20:21

2 Answers2

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}']`; 
Alexander Nied
  • 12,804
  • 4
  • 25
  • 45
0
query = 'input[value="' + x + '"]';

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

Barmar
  • 741,623
  • 53
  • 500
  • 612
Jay Lane
  • 1,379
  • 15
  • 28