Dealing with form element values

Because form elements have special properties, jQuery’s core contains a number of convenience functions for activities such as these:

  • Getting and setting their values
  • Serializing them
  • Selecting elements based on form-specific properties

What’s a form element?

When we use the term form element, we’re referring to the elements that can appear within a form, possess name and value attributes, and whose values are sent to the server as HTTP request parameters when the form is submitted.

Let’s take a look at one of the most common operations you’ll want to perform on a form element: getting access to its value. jQuery’s val() method takes care of the most common cases, returning the value attribute of a form element for the first element in the jQuery object. Its syntax is as follows.

Method syntax: val
val()
Returns the current value of the first element in the jQuery collection. If the first element is a <select> and no option is selected, the method returns null. If the element is a multiselect element (a <select> having the multiple attribute specified) and at least one option is selected, the returned value is an array of all selected options.
Parameters
none
Returns
The fetched value or values.

This method, although quite useful, has a number of limitations of which you need to be wary. If the first element in the set isn’t a form element, an empty string is returned, which some of you may find misleading. This method doesn’t distinguish between the checked or unchecked states of check boxes and radio buttons and will return the value of check boxes or radio buttons as defined by their value attribute, regardless of whether they’re checked or not.

For radio buttons, the power of jQuery selectors combined with the val() method saves the day. Consider a form with a radio group (a set of radio buttons with the same name) named radio-group and the following expression:

$('input[type="radio"][name="radio-group"]:checked').val();

This expression returns the value of the single checked radio button (or undefined if none are checked). That’s a lot easier than looping through the buttons looking for the checked element, isn’t it?

Because val()considers only the first element in a set, it’s not as useful for check box groups where more than one control might be checked. But jQuery rarely leaves you without recourse. Consider the following:

var checkboxValues =
   $('input[type="checkbox"][name="checkboxgroup"]:checked').map(function() {
      return $(this).val();
   })
   .toArray();

Although the val() method is great for obtaining the value of any single form control element, if you want to obtain the complete set of values that would be submitted through a form submission, you’ll be much better off using the serialize() or serializeArray() methods (which you’ll see in lesson 10).

Another common operation you’ll perform is to set the value of a form element. The val() method is also used for this purpose by supplying a value. Its syntax is as follows.

Method syntax: val
val(value)
Sets the passed value as the value of all matched elements. If an array of values is provided, it causes any check boxes, radio buttons, or options of select elements in the set to become checked or selected if their value properties match any of the values passed in the values array.
Parameters
value(String|Number|Array|Function) Specifies the value that is to be set as the value property of each element in the set. An array of values will be used to determine which elements are to be checked or selected. If a function, the function is invoked for each element in the set, with that element passed as the function context (this), and two values: the element index and the current value of the element. The value returned from the function is taken as the new value to be set.
Returns
The jQuery collection.

As the description of the method specifies, the val() method can be used to cause check box or radio elements to become checked or to select options within a <select> element. Consider the following statement:

$('input[type="checkbox"], select').val(['one', 'two', 'three']);

It’ll search all the checkboxes and selects on the page for values that match any of the input strings: "one""two", or "three". Any element found that matches will become checked or selected. In case of a select element without the multiple attribute defined, only the first value to match is selected. In our previous code only an option having a value of one is selected because in the array passed to val() the string "one" comes before the strings "two" and "three". This makes val() useful for much more than the text-based form elements.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *