better software through user-centered design

jQuery Form Serializer

This serializer is an example of how we can use form elements and jQuery data() to manipulate page data and let MVC3 automatically bind it to the model. Note the compensation for MVC3’s handling of checkboxes and checkbox logic.

/// Walks through form and creates JSON object from input elements and optional data elements.
/// These objects are able to be bound to the view model by MVC 3.
Serialize: function (options) {
var returnJson = {};

this.find(‘:input’).each(function (i) {
var item = $(this);
if (item.attr(“name”)) {
//this logic compensates for MVC3 adding a hidden after every checkbox.
if (!returnJson[item.attr(“name”)] || (returnJson[item.attr(“name”)] && !item.attr(“type”) == ‘hidden’)) {
if (item.attr(“type”) == “checkbox”) {
returnJson[item.attr(‘name’)] = item.is(“:checked”);
} else {
returnJson[item.attr(‘name’)] = item.val();
}
}
}
});

/// Add data() elements to json object if exists.
/// You can attach data elements to the form to add to the post to get model bound.
/// Example: $(“#MyForm”).data(“ToPost”, {MyobjKey: ‘myvalue’}, {MyArray: []});
if (this.data(“ToPost”)) {
$.each(this.data(“ToPost”), function (key, value) {
returnJson[key] = value;
});
}

return returnJson;
}, ///end SerializeForm

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: