views:

474

answers:

2

I have the following DOM structure..

<input id="WorkAssignmentID_3462" type="hidden" value="3462" name="WorkAssignmentID"/>
<input id="WorkItemID_3462" type="hidden" value="3633" name="WorkItemID"/>
<input id="EmployeeID_3462" type="hidden" value="15" name="EmployeeID"/>
<input id="AssignedBy_3462" type="hidden" value="Jonathan Erickson" name="AssignedBy"/>
<input id="AssignedDate_3462" type="hidden" value="8/1/2009 12:00:00 AM" name="AssignedDate"/>
<input id="ExpirationDate_3462" type="hidden" value="" name="ExpirationDate"/>
<input id="RegisteredDate_3462" type="hidden" value="8/1/2009 12:00:00 AM" name="RegisteredDate"/>

lets just say the jQuery selector to get all of those DOM elements is the following:

$('#assignment');

and what I want to do is create a JSON object from that set:

var WA = {
    WorkAssignmentID: '3462',
    WorkItemID: '3633',
    EmployeeID: '15',
    AssignedBy: 'Jonathan Erickson',
    AssignedDate: '8/1/2009 12:00:00 AM',
    ExpirationDate: '',
    RegisteredDate: '8/1/2009 12:00:00 AM',
};

what would be the easiest way to do that?

I was thinking of doing something like this, but it doesn't work because I don't think that you can dynamically create the property of the JSON object... is it possible to dynamically create the property name?

var WA = {};

$('#assignment').each(function(idx, elem) {
    $.extend(WA, {
                     $(elem).attr('name'): $(elem).val()
                 });
});
+2  A: 

What about this, using the bracket notation:

var result = {};

$('input[type=hidden]').each(function() {
    result[this.name] = this.value;
});
CMS
thank you, i was definitely over-complicating the solution haha.
Jon Erickson
Careful here, using `this` explicitly can break depending on the context that executes the above code. That's why $.each() provides the element to the callback as an argument.
Peter Bailey
No, in the context of the callback function *this* is always the DOM element, since internally jQuery invokes the callback funciton usin call: `callback.call( object[ name ], name, object[ name ] )`, check the each function implementation on jquery-1.3.2.js (line 672).
CMS
+2  A: 

Calling $.extend() is overkill, IMO. But you've got the basic approach I'd use

var WA = {};
$('input[type="hidden"]').each( function( idx, elem )
{
  WA[elem.name] = elem.value;
}
Peter Bailey