For the ride and powerful voodoo

JQuery.obj() – Converting inputs to a javascript object

For a while now I’ve been using a JQuery extension that takes selected inputs (and dropdowns and textareas) or inputs contained in the selection and converts them into a javascript object ready for submission with an Ajax post as JSON.

The need for something like this came about when we found that the data that needed to be submitted didn’t neatly fit on a form. An example is where the data was across multiple tabs and the “submit” button needed to be on the first tab.

Now, we have the ability to use the following JQuery:

var newObj = $('#tab1,#tab2,#tab3').obj();

to grab all the inputs into an object, which can then be manipulated before submission. Inputs of type “button” and anything you mark with the class “ignore” won’t be pulled into the object.

The construction of the object is based on the names of the inputs, and follows the dot and bracket notation used in naming .Net MVC, so the following inputs:

unless of course the “preserveNaming” option is passed in and set to true. In which case the object will be flat, and you’ll get names like “m1.Sub1.Numbers[0]”. Using something like json2, you can stringify this and submit it in an ajax call. It plays very nicely with .Net MVC.

It’s worth pointing out that the JQuery selector can incorporate controls and containers, so you can do something like this: