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
  • 5,590
  • 8
  • 40
  • 80
  • `$("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
  • 11,309
  • 4
  • 26
  • 41
0
query = 'input[value="' + x + '"]';

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

Barmar
  • 669,327
  • 51
  • 454
  • 560
Jay Lane
  • 1,341
  • 14
  • 28