I've got a HTML page containing elements that I need to access using JQuery. Here is an example of how the form elements are identified:
<div id="nItemID[766]Line" class="formLine ">
<span id="nItemID[766]Label" class="formLabel alignTop">Téléphone:</span>
<input id="nItemID[766]Field" class="formField" type="text" maxlength="11" value="" name="nItemID[766]" style="width: 300;">
</div>
When I try to show the ID of a particular element, it tells me: nItemID[766]Label, for example. But when I type that code, it doesn't find anything...
alert( $("#nItemID[766]Field").val() );
Could someone help me with the way to access those particular elements ?
Thank you!
You'll have to escape the square brackets with backslashes:
It's a little bit questionable to have "id" values like that, but I've been in situations in which they're hard to avoid.
edit — note that you need two backslashes in the string so that the jQuery selector interpreter can "see" them; that is, you need to leave a single backslash in the string, and the way to do that in JavaScript is to double the backslash I hate explaining that.
edit again — Here's what the HTML 5 draft has to say about "id" attributes:
No rules about the values of "id" attributes, in other words, other than that they cannot contain spaces.
That is invalid HTML.
[
and]
are not valid characters in ids. You can use them in names like you already do on your input element, but not in ids.You should change your ids to be something like
nItemID_766_Field
. Then it will be a valid id and you can easily just change the number for each nItem.Edit
As Pointy pointed out it is valid in HTML 5. So you shouldn't need to change your id's unless you are trying to conform to HTML 4.
Try instead
document.getElementById("nItemID[766]Field").value
. Apparently jQuery doesn't support ids with braces.Your IDs are invalid, see this.