4

I'm working with jQuery and I have this element:

<input class="css-checkbox" id="services[3492][selected]" name="services[3492][selected]" type="checkbox" value=" 1">

When I try to get that item in my console through its ID — services[3492][selected] — I get an empty response: [].

Code:

$('#services[3490][selected]') // Not working
$('[id*="services[3490][selected]"') // Working

I think it's because the [ characters. Maybe I need to sanitize, or use some escape characters or unicode transformation.

Baumannzone
  • 760
  • 2
  • 19
  • 38
  • 1
    `$('[id*="services[3490][selected]"')` is missing a closing `]` after the `"`. is that accurate, and working even so? – doppelgreener Nov 02 '16 at 17:16

3 Answers3

5

You need to escape the metacharacters( such as !"#$%&'()*+,./:;<=>?@[\]^{|}~ ) in jquery selector using \\.

$('#services\\[3490\\]\\[selected\\]')


From jQuery selecctors 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"). The W3C CSS specification contains the complete set of rules regarding valid CSS selectors. Also useful is the blog entry by Mathias Bynens on CSS character escape sequences for identifiers.

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
4

Per jquery documentation,

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \.

To use brackets in the first example, I believe your selector would need to be:

$('#services\\[3490\\]\\[selected\\]')

Nick G
  • 1,953
  • 12
  • 16
3

You need to escape the square brackets in the id selector so they are not interpreted as attribute selectors:

$('#services\\[3490\\]\\[selected\\]')
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339