Snowing Code

Personal notes on software development

JQuery id with unauthorised characters

(Publish date: 31/12/2009)

Yesterday was the second time I’ve found myself staring at the screen trying to figure out what just went wrong there, which in my book is the best trigger for writing a post. The problem is very simple:

In ASP.NET MVC, in order to get a collection (list/array/dictionary etc’) property of your view-model out back to the controller, you need to have your TextBox (or whatever) id attribute looking like this:

<input ... id="MyList[0].Name" ... />

More about it can be found here. Now, all is working nice and tidy until you bring JQuery in, which will not let you select such an object by its id (or any id that contains selector characters such as ‘.’, ‘:’ and so on) , so that the following code will return null:


My almighty, kind and generous boss has came up with a bit of code that will override this behviour, which I took liberties to refactor in order to take care of the ‘.’ and ‘:’ cases (even though dots shouldn’t really be a part of the id since the HtmlHelper extension methods in MVC replace dots with an underscore)-

function $$(selector, context) {
           return jQuery(selector.replace(/(\[|\]|:|\.)/g, '\\$1'), context)

So that all you need to do is:


tidy! :-)

blog comments powered by Disqus