A repository of over 1000 quality jQuery plugins

jQuery .val()

Learn all about the jQuery function .val().

The .val() method is primarily used to get the values of form elements such as input, select and textarea. In the case of select elements, it returns null when no option is selected and an array containing the value of each selected option when there is at least one and it is possible to select more because the multiple attribute is present.

For selects and checkboxes, you can also use the :selected and :checked selectors to get at values, for example:

1
2
3
4
5
6
7
8
9
10
11
// Get the value from a dropdown select
$( "select.foo option:selected").val();
// Get the value from a dropdown select even easier
$( "select.foo" ).val();
// Get the value from a checked checkbox
$( "input:checkbox:checked" ).val();
// Get the value from a set of radio buttons
$( "input:radio[name=bar]:checked" ).val();

Note: At present, using .val() on textarea elements strips carriage return characters from the browser-reported value. When this value is sent to the server via XHR however, carriage returns are preserved (or added by browsers which do not include them in the raw value). A workaround for this issue can be achieved using a valHook as follows:

1
2
3
4
5
$.valHooks.textarea = {
get: function( elem ) {
return elem.value.replace( /r?n/g, "rn" );
}
};