Question

I am trying to use a variable for name with brackets and getting nowhere.

I have this html

<select name="option[123]">
  <option value="45">Red</option>
  <option value="49">Blue</option>
</select>

With jQuery, I need to access the select by name so I do:

$('select[name="option\\[123\\]"]').change();

that works fine as it uses the double slash method as directed by jQuery's guide.

But I need the option to be a variable, So I've tried:

var myname = "option\\[123\\]";
$('select[name="+myname+"]').change();

But it doesn't work.

I've tried without the slashes, I've tried doubling and tripling the slashes... all the way up to 12 slashes each bracket... and it causes javascript error or simply doesn't work.

How can I set a variable to that bracketed option name?

Was it helpful?

Solution

You are missing a ', and by the way, when you use " you don't need to escape the brackets.

Try this:

var myname = "option[123]";
$('select[name="'+myname+'"]').change();
                ^        ^ 

Fiddle

OTHER TIPS

Try this:

$("select[name=" +myname + "]").change();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top