Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .val() returns undefined at complex id

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?

like image 966
Lars Avatar asked Dec 21 '22 17:12

Lars


2 Answers

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/

like image 183
Naftali Avatar answered Jan 05 '23 09:01

Naftali


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.

like image 31
Šime Vidas Avatar answered Jan 05 '23 07:01

Šime Vidas