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?

有帮助吗?

解决方案

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

其他提示

Try this:

$("select[name=" +myname + "]").change();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top