HTML and CSS Reference
In-Depth Information
The first task of this function will be to extract all the form fields from the form this func-
tion is called on (which again, will be represented by the this variable. We can extract the
input fields with the following:
this.find('input')
The only problem is that this will not include select boxes, since they are not considered
types of input fields. Fortunately, jQuery provides a selector that does return all input fields,
including select fields:
this.find(':input')
Once all the form fields are found, the implementation will iterate over all the fields and
extract their name attribute. It will then look in the object for a property with that name,
and if there is one, it we will set the value of the field from the value of the property:
fromObject: function(obj) {
$.each(this.find(':input'), function(i,v) {
var name = $(v).attr('name');
if (obj[name]) {
$(v).val(obj[name]);
} else {
$(v).val('');
}
});
}
You will notice that we add the $() construct around the references to v . This is because the
value returned is a native DOM object; therefore it is necessary to convert them to jQuery
objects in order to use the attr method.
With that implementation in place you should be able to change values in the form, and
then call the following to repopulate it back to the original values stored in the o variable:
> $('form').fromObject(o)
The final version of the jQuery plugin is as follows:
(function($) {
$.fn.extend({
toObject: function() {
var result = {}
$.each(this.serializeArray(), function(i, v) {
Search WWH ::




Custom Search