.val()返回类型:String or Number or Array
描述:取得匹配的元素集合中每一个元素的当前值。
.val()
方法主要用来取得表单元素,譬如input
、select
和textarea
的值。如果在空集合上调用它,就返回undefined
。
如果集合中的第一个元素是一个多选元素(亦即,一个<select>
元素,设置了multiple
特性),则.val()
返回一个数组,包含了每个选中的选项的值。自从jQuery 3.0以来,如果没有选中选项,它返回一个空数组;在jQuery 3.0以前,它返回null
。
对于下拉选框、勾选框和单选钮,你可以使用:checked来选择正确的元素。例如:
1
2
3
4
5
6
7
8
9
10
11
|
|
注意:在当前,使用<textarea>
元素上的.val()
将剥除回车,返回浏览器报告值的字符。铸成,如果此值通过XHR发送到服务器,返回的回车符会被保留(或者由浏览器添加,它在原始值中不包含它们)。对于这个问题的变通方法,可以通过使用valHook来实现,如下所示:
1
2
3
4
5
|
|
示例:
从单选下拉选框中取得单一的值,从多选下拉选框中选择值的数组,并显示它们的值。
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
41
42
43
44
45
46
47
|
|
演示:
找到输入框的值。
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
|
|
演示:
.val( value )返回类型:jQuery
描述:设置每个匹配的元素的值。
-
增补版本:1.0.val( value )
-
valueA string of text, a number, or an array of strings corresponding to the value of each matched element to set as selected/checked.
-
-
增补版本:1.4.val( function )
-
functionA function returning the value to set.
this
is 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.
val()
allows you to pass an array of element values. This is useful when working on a jQuery object containing elements like <input type="checkbox">
, <input type="radio">
, and <option>
s inside of a <select>
. In this case, the input
s and the option
s having a value
that matches one of the elements of the array will be checked or selected while those having a value
that doesn't match one of the elements of the array will be unchecked or unselected, depending on the type. In the case of <input type="radio">
s that are part of a radio group and <select>
s, any previously selected element will be deselected.
Setting values using this method (or using the native value
property) does not cause the dispatch of the change
event. For this reason, the relevant event handlers will not be executed. If you want to execute them, you should call .trigger( "change" )
after setting the value.
The .val()
method allows setting 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 removes leading and trailing whitespace from the values of text inputs with a "tags" class.
示例:
设置一个输入框的值。
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
|
|
演示:
使用函数参数来修改一个输入框的值。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
|
演示:
设置一个单选下拉选框、多选下拉选框架、勾选框和单选钮的值。
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
|
|