
Creating a query string automatically for all form elements
Getting ready
Create a new folder Recipe2
inside the chapter2
directory. Now create a file index.html
in the newly created directory.
How to do it...
- Open the
index.html
file for editing and create a form with some HTML elements, such as textboxes, radio buttons, and check boxes.<html> <head> <title>Serializing form values</title> <style type="text/css"> ul{ border:1px solid black; list-style: none;margin:0pt;padding:0pt;float:left;font-family:Verdana,Arial, Helvetica, sans-serif;font-size:12px;width:400px;} li{ padding:10px 5px;border-bottom:1px solid black;} label{width:100px;text-align:right;margin-right:10px;float:left;} </style> </head> <body> <form> <ul> <li><label>Email:</label><input type="text" name="email"/></li> <li><label>Full Name</label><input type="text" name="fullName"/></li> <li> <label>Sex</label> <input type="radio" name="sex" value="M"/>Male <input type="radio" name="sex" value="F"/>Female </li> <li> <label>Country</label> <select name="country"> <option value="IN">India</option> <option value="UK">UK</option> <option value="US">USA</option> </select> </li> <li> <label>Newsletter</label> <input type="checkbox" name="letter"/>Send me moreinformation</li> <li> <input type="button" value="GO"/> </li> </ul> </form> </body> </html>
- Once again include the link to the jQuery file. After that add an event handler for the input button that we have placed on the form. This button will use the
serialize()
method on the form and will alert the resulting query string.<script type="text/javascript" src="../jquery.js"></script> <script type="text/javascript"> $(document).ready(function () { $('input:button').click(function() { alert($('form:first').serialize()); }); }); </script>
- Open your browser and run the
index.html
file. Fill the form and click on the GO button. The browser will display the values of form elements in a query string format, as shown in the following screenshot:
How it works...
The serialize()
method of jQuery turns form elements into query string format. Rather than getting each value manually and creating a query string, this function can be very handy when you want to send the values of all form elements as a part of AJAX requests. You can use any of the methods like GET or POST to send this data to the server.
There's more...
Another useful function for getting values of form elements is serializeArray()
. This function turns all the elements into a JavaScript object.
var data = $('form:first').serializeArray();
If the form has two textboxes named input1
and input2
and their values are value1
and value2
respectively then the object will be created as shown below:
[ { input1: 'value1' }, { input2: 'value2' }, ]
Remember that Submit buttons and File select elements are not serialized.
See also
- Fetching data from PHP using jQuery
- Sending data to PHP