4

I have two hidden input fields:

<input type="hidden" name="institut" id="institut" value="blablub" />
<input type="hidden" name="institut[0]" id="institut[0]" value="moreblablub" />

I have this debugging code:

console.log("#institut: " + $("#institut").val());
console.log("#institut[0]: " + $("#institut[0]").val());

And I get this console output:

#institut: blablub
#institut[0]: undefined

I trid to escape the square brackets with backslashes but that did not change anything. Is there a way to get hold of complex ID's?

Lars
  • 63
  • 1
  • 6
  • 3
    Try `$("#institut\\[0\\]").val()` – Šime Vidas Aug 20 '12 at 13:20
  • Actually, it's not allowed to use `[` and `]` characters in ID identifier. So even if you fix this code, it might got broken someday. Why don't just use another separator, like '-' or '_'? – raina77ow Aug 20 '12 at 13:23
  • @raina77ow Could you provide a source? I haven't found any such restrictions in the HTML standard. – Šime Vidas Aug 20 '12 at 13:30
  • @ŠimeVidas here: http://stackoverflow.com/a/1077111/561731 – Naftali Aug 20 '12 at 13:34
  • 1
    @Neal That answer cites the HTML 4 standard. HTML 4 was an application of SGML. The title of the cited section is "SGML Basic Types", and in it, the ID token is specified. However, HTML is no longer an application of SGML, so those rules no longer apply. I've been searching in the HTML Living Standard, and the [corresponding section](http://www.whatwg.org/specs/web-apps/current-work/multipage/elements.html#the-id-attribute) states that the value of the "id" attribute must contain at least one character, and no space characters. I haven't found any other restrictions. – Šime Vidas Aug 20 '12 at 13:49

3 Answers3

8

You should not be using non alphanumeric characters for an id.

But if you do you can do:

var element = document.getElementById("institut[0]");
var $element = $(element);

Demo: http://jsfiddle.net/maniator/sWnJN/

Or

var $element = $("#institut\\[0\\]");

Demo: http://jsfiddle.net/maniator/sWnJN/1/

Or even:

var $element = $("[id='institut[0]']");

Demo: http://jsfiddle.net/maniator/sWnJN/2/

Naftali
  • 144,921
  • 39
  • 244
  • 303
2

You have to escape the brackets:

$( '#institut\\[0\\]' ).val()

Live demo: http://jsfiddle.net/Qsagn/

Brackets are special characters in CSS - they define attribute selectors. You need to double-escape the brackets. A single escape \[ is not enough, since the \ character is a special character in string literals, so you need \\ in order to escape the \ character, so that it is interpreted as a literal character.

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
1

You can always use document.getElementsByName("institut[0]")[0].value.

João Silva
  • 89,303
  • 29
  • 152
  • 158