views:

129

answers:

3

I am using ASP.Net MVC which has created an id for a textbox for an object which is deep within my object tree as follows:

<input id="evt_SessionLinks[0]_Sessions[0]_TimeTables[0]_TimeWindows[0]_Finish" name="evt.SessionLinks[0].Sessions[0].TimeTables[0].TimeWindows[0].Finish" type="text" value="" class="clockPick"/>

I am trying to select this field with the following Jquery selector:

var e = $("#evt_SessionLinks[0]_Sessions[0]_TimeTables[0]_TimeWindows[0]_Finish");

If I run my code, place a breakpoint and inspect e the variable is show to have length of 0.

If I change the id and selector to be id='Finish'/'#Finish'. Then length = 1.

I think I am attempting to select the element correctly? Is there some sort of restriction on the length of id that the selector can find?

+1  A: 

I think the issue is the square brackets, not the length of the selector. Try escaping the square brackets with a "\".

UPDATE: According to this blog post, you need two "\"s, not one. My inference would be that there needs to be a "\" there still when JQuery interprets it, and that backslash would be flattened away by the JavaScript parser.

var e = $("#evt_SessionLinks\\[0\\]_Sessions\\[0\\]_TimeTables\\[0\\]_TimeWindows\\[0\\]_Finish");
kcrumley
Of course, thanks. BTW to escape the [ ] a double backslash is required: '\\'
Richbits
Hmm, was making that update while you were commenting. :D
kcrumley
+2  A: 

The "[...]" portion of the selector is interpreted as a test on the attribute of the element. This turns the query into something that wouldn't ever work.

If you really have the square brackets in your code, you'll need to remove them in order to use this. IDs like "Area01_Section02_Line03" are not uncommon.

John Fisher
The square brackets are a requirement for the default model binder within the asp.net mvc framework to map to collections, escaping the square brackets does work correctly.
Richbits
+1  A: 

Maybe because it's an invalid id?

From the w3c spec:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

seth
Interesting, though this is the specified approach for asp.net mvc default model binder AFAIK. The brackets don't cause any issues in FF/IE/Safari.
Richbits
Hmm, that's kind of weird but not really surprising I guess. Turns out I was wrong anyways.
seth