.val()Returns: String or Number or Array
Description: Get the current value of the first element in the set of matched elements.
The .val() method is primarily used to get the values of form elements such as input, select and textarea. In the case of <select multiple="multiple"> elements, the .val() method returns an array containing each selected option; if no option is selected, it returns null.
For selects and checkboxes, you can also use the :selected and :checked selectors to get at values, for example:
|
1
2
3
4
|
|
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
|
|
Examples:
Example: Get the single value from a single select and an array of values from a multiple select and display their values.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
|
Demo:
Example: Find the value of an input box.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
|
Demo:
.val( value )Returns: jQuery
Description: Set the value of each element in the set of matched elements.
-
version added: 1.0.val( value )
-
valueA string of text or an array of strings corresponding to the value of each matched element to set as selected/checked.
-
-
version added: 1.4.val( function(index, value) )
-
function(index, value)Type: Function()A function returning the value to set.
thisis the current element. Receives the index position of the element in the set and the old value as arguments.
-
This method is typically used to set the values of form fields.
Passing an array of element values allows matching <input type="checkbox">, <input type="radio"> and <option>s inside of n <select multiple="multiple"> to be selected. In the case of <input type="radio">s that are part of a radio group and <select multiple="multiple"> the other elements will be deselected.
The .val() method allows us to set the value by passing in a function. As of jQuery 1.4, the function is passed two arguments, the current element's index and its current value:
|
1
2
3
|
|
This example appends the string " items" to the text inputs' values.
Examples:
Example: Set the value of an input box.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
|
Demo:
Example: Use the function argument to modify the value of an input box.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
|
Demo:
Example: Set a single select, a multiple select, checkboxes and a radio button .
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
|