This function assists with common idioms encountered when performing AJAX tasks.
Encodes a set of form elements as a string for submission. .serialize(param) |
The .serialize()
method creates a text string in standard URL-encoded notation. It operates on a jQuery object representing a set of form elements. The form elements can be of several types:
<form> <div><input type="text" name="a" value="1" id="a" /></div> <div><input type="text" name="b" value="2" id="b" /></div> <div><input type="hidden" name="c" value="3" id="c" /></div> <div><textarea name="d" rows="8" cols="40">4</textarea></div> <div><select name="e"> <option value="5" selected="selected">5</option> <option value="6">6</option> <option value="7">7</option> </select></div> <div><input type="checkbox" name="f" value="8" id="f" /></div> <div><input type="submit" name="g" value="Submit" id="g"> </form>
We can serialize all of these element types after selecting them:
$('form').submit(function() { $(this).log($('input, textarea, select').serialize()); return false; });
This produces a standard-looking query string:
a=1&b=2&c=3&f=8&g=Submit&d=4&e=5
The string is close to, but not exactly the same as, the one that would be produced by the browser during a normal form submission. The .submit()
method uses the .name
and .value
properties of each element to create the string, so in cases where these properties do not reflect the actual form values, the string can be incorrect. For example, the checkbox in the example above always has a .value
of 8
, whether or not the box is checked.
For a more robust solution, the form plug-in is available. Its methods provide an encoding that matches the one provided by a browser.