I'm working on a legacy system that uses square brackets in id parameters. E.g.:
<select id="mySelect[]">
<option value="1">Yadda</option>
<option value="2">Yadda</option>
<option value="3">Yadda</option>
</select>
jQuery (being javaScript) quite rightly complains when I try to use this id in, say,
$("#mySelect[]").append(options);
Given the fact that I can't change the legacy code and therefore I'm stuck with the existing id's (which may or may not be valid in any context), what would be a good way to work around this mess and let me select my elements?
While using meta characters you have to escapse those.
$("#mySelect\\[\\]").append(options);
Jquery selector docs saying that
To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \.
If you don't want to escape it, you can use the selector
$( document.getElementById('mySelect[]')
Try this way:
$("#mySelect\\[\\]").append(options);
You need to escape [
and ]
as they are reserved jquery chars used in selectors.
Have a look at the jquery docs
To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \. For example, an element with id="foo.bar", can use the selector $("#foo\.bar").
and a fiddle here
Plus ofcourse you could do this $('[id="mySelect[]"]')
But since it is an attribute selector performance wise this will be slower and you lose the advantage of using the id selector, but handy if you are in no way to escape the chars.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With