1

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 Answers 2

3

What about this, using the bracket notation:

var result = {};

$('input[type=hidden]').each(function() {
    result[this.name] = this.value;
});
Sign up to request clarification or add additional context in comments.

3 Comments

thank you, i was definitely over-complicating the solution haha.
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.
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).
2

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.