HTML and CSS Reference
In-Depth Information
Inside the function we can use the this variable to access the element or elements that the
function has been executed on, for instance in the example above, all the div elements. This
will either represent an array of jQuery elements, or a single jQuery element. In our ex-
ample we are always going to assume that this is a single element.
To begin, we will write a rudimentary version of the serialize function that simply writes
the contents of the form to the console log:
(function($) {
toObject: function() {
This implementation adds a new function to jQuery called toObject , and is going to take
advantage of a function already available in jQuery that serializes a form into a string.
Add this to the script section of the web page, refresh the web page, and click “Add task”.
Enter values into all the fields, and then call:
> $('form').toObject()
This should print out a text string with the contents of the form.
Now that we have a basic implementation, we can start writing the code needed to return
an object with properties populated from the form.
Although jQuery does not have a function for serializing a form into an object, it does have
a function for serializing a form to an array. This function returns an array where each form
field is represented by an element in the array, and consists of a name and a value. In order
to see this function in action, execute the following:
> $('form').serializeArray()
We will use this as the basis of our implementation, and iterate over the array using a
jQuery helper function called each :
$.each($('form').serializeArray(), function(i, v) {
Search WWH ::

Custom Search