Skip to content Skip to sidebar Skip to footer

Javascript Array Id's

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:
alert($('#nItemID\\[766\\]Field').val());

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:

3.2.3.1 The id attribute

The id attribute specifies its element's unique identifier (ID). [DOMCORE]

The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.

An element's unique identifier can be used for a variety of purposes, most notably as a way to link to specific parts of a document using fragment identifiers, as a way to target an element when scripting, and as a way to style a specific element from CSS.

Identifiers are opaque strings. Particular meanings should not be derived from the value of the id attribute.

No rules about the values of "id" attributes, in other words, other than that they cannot contain spaces.

Solution 2:

Your IDs are invalid, see this.

Solution 3:

Try instead document.getElementById("nItemID[766]Field").value. Apparently jQuery doesn't support ids with braces.

Solution 4:

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.

Post a Comment for "Javascript Array Id's"