Pregunta

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?

¿Fue útil?

Solución

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

Otros consejos

Try this:

$("select[name=" +myname + "]").change();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top