0

I have a form set up like this in HTML:

<input type="text" name="data[type1][0]" value="" size="20" id="data[type1][0]"/>
<input type="text" name="data[type1][1]" value="" size="20" id="data[type1][1]"/>

I set up this way so $_POST['data'] would become an array in php.

Are there ways to select specific elements or the whole set of elements in jQuery?

I've tried $("#data[type1][0]").css("visibility","visible"); but it doesn't work does not work.

Thanks in advance!

rickypai
  • 4,016
  • 6
  • 26
  • 30
  • 1
    you might try this post: http://stackoverflow.com/questions/1239095/find-dom-element-by-id-when-id-contains-square-brackets – awongh Feb 17 '11 at 03:15

2 Answers2

4

Brackets are jQuery meta-characters, you must escape them with two backslashes:

$("#data\\[type1\\]\\[0\\]").css("visibility","visible");
The Scrum Meister
  • 29,681
  • 8
  • 66
  • 64
  • +1, proof: http://jsbin.com/udizi5 (the input disappears after a second, when the selector runs). And more: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier – T.J. Crowder Feb 17 '11 at 03:17
  • @shiroin Yes. The list of meta characters are defined here http://api.jquery.com/category/selectors/ – The Scrum Meister Feb 17 '11 at 03:17
  • *"you must escape them with two backslashes"* More accurately: In the selector, you must escape a `[` with a backslash, and since this is a JavaScript string literal, to write an actual backslash you have to escape it (with a backslash). – T.J. Crowder Feb 17 '11 at 03:18
2

You need to double-escape the brackets

$("#data\\[type1\\]\\[0\\]").css("visibility","visible");

Also, [ and ] are invalid characters in the id-attributes in HTML4/XHTML.

  • Are you sure they are invalid inside the id attribute? the sample T.J. provided seams to work/ – The Scrum Meister Feb 17 '11 at 03:18
  • @The Scrum Meister: I think that's jQuery being nice. `[` and `]` are valid in **HTML** `id` values, but *CSS* is much more restrictive: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier @arex1337: It's perfectly valid HTML: http://www.w3.org/TR/html5/elements.html#the-id-attribute That said, for `id` values I'm going to use in selectors in jQuery, since jQuery's selectors are CSS plus some enhancements, I tend to stick to valid *CSS* `id` values. – T.J. Crowder Feb 17 '11 at 03:21
  • @The Scrum Meister: I thought it was jQuery being nice (about the CSS `id` value), but that section of the CSS spec isn't very clear (this isn't unusual for the CSS spec), and if jQuery's being nice, looks like the major browsers are too: http://jsbin.com/amowa The "this is foo[bar]" element has `id="foo[bar]"` and a style rule with the selector `#foo\[bar\]`. The rule applies (shows the text in blue) on IE6/7/8, Chrome, Firefox, and Opera, so perhaps they're okay. The [validator](http://jigsaw.w3.org/css-validator) seems to accept them too, though I can't be sure how it's interpreting it. – T.J. Crowder Feb 17 '11 at 03:44