Gr3go Gr3go - 2 years ago 109
Javascript Question

Selecting a nested input tag retrieves jQuery object but all attributes undefined

As requested, I created a jsFiddle example to show this in action:

Given the following (stripped down) HTML within a table:

<table id="aTable">

<tr id="editFormula-formulaResource-0" class="editFormula_formulaResource">
<input id="anArrayid[0].field1" name="name1" value="20" type="hidden">
<input id="anArrayid[0].field2" name="name2" value="1" type="hidden">
Required Count:
<input id="anArrayid[0].field3" name="name3" value="3" type="text">

<input type="button" class="jquery-button" id="newRow" value="Add New Row" onClick="addRow()" />

Why is the value attribute returning undefined instead of 0 or "0" from within the javascript/ jQuery? (I have since added @GertG's suggestion regarding the illegal characters, it now works in jsFiddle).

function addRow() {

var idx = 1;

var $resourceCountSelector
target = "#anArrayid\\[" + String(idx - 1) + "\\]\\.field3";
$resourceCountSelector = $(target);

//code that was removed is the code that does the cloning, but as the issue reproduces without it, I left it out as extraneous.


What am I doing wrong here?

Note: Firefox 46.0.1 on Mac 10.7.5
I saw some other explanations that appear wonky, so perhaps it is a browser/platform thing? Seems like this is so basic though, I can select other tags fine. #jQueryNoob.

Answer Source

Although brackets and periods are perfectly valid in html ids, they have special meanings in jQuery selectors, so you need to escape them with double backslashes.

target = "#anArrayid\\[" + String(idx - 1) + "\\]\\.field3";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download