Getting data from forms with jQuery

jQuery can be used to simplify how data is extracted from HTML forms. This makes the task of validating user input much simpler than when using only JavaScript.

The val() method

The jQuery val() method greatly simplifies the grabbing of data from form elements. For example, in order to grab the selected value from a <select> list using JavaScript the following is required:

// get value from a select control - JavaScript style
var selectindex = document.forms.jsform.albums.selectedIndex;
var selectvalue = document.forms.jsform.albums.options[selectindex].value;

The same action using jQuery looks like this:

// much shorter jQuery style select value grab
var selectvalue = $('select[name=albums]').val();

Live example

Please select a CD!

This example has an onchange() event. Try changing the control and then changing it back to its default position.

This is a good example of a <select> which will require validation as the default value of "Please select a CD!" is not a lot of use to anyone wanting to collect that data.

The val() method can be used with any of the HTML form controls making the extraction of values from form element very much more straightforward. For example this jQuery code:


... extracts the value from a textbox, textarea or a select element, with only a small addition:


... extracts the value from selected checkboxes or radio buttons.

Live example

This example uses the above two examples of code to extract the values from the form below when the "Get Results" button is clicked. View source and scroll to line #128 to see how these code examples are used.

Appetite for Destruction
Licence to Ill
Hairway to Steven


Now open the jQuery forms exercise page and work through it.

You will need to use the jQuery documentation, specifically the val() method.

You may also use the JavaScript scratch pad to try out code quickly.