.serializeArray()


.serializeArray()傳回:陣列

說明:將一組表單元素編碼為名稱和值的陣列。

.serializeArray() 方法會建立一個 JavaScript 物件陣列,準備編碼為 JSON 字串。它會對 form 和/或表單控制項的 jQuery 集合進行操作。控制項可以是下列幾種類型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<form>
<div><input type="text" name="a" value="1" id="a"></div>
<div><input type="text" name="b" value="2" id="b"></div>
<div><input type="hidden" name="c" value="3" id="c"></div>
<div>
<textarea name="d" rows="8" cols="40">4</textarea>
</div>
<div><select name="e">
<option value="5" selected="selected">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select></div>
<div>
<input type="checkbox" name="f" value="8" id="f">
</div>
<div>
<input type="submit" name="g" value="Submit" id="g">
</div>
</form>

.serializeArray() 方法使用 成功控制項 的 W3C 標準規則來決定應包含哪些元素;特別是元素不能停用,且必須包含 name 屬性。由於表單並未使用按鈕提交,因此不會序列化任何提交按鈕值。不會序列化檔案選取元素的資料。不包含 value 屬性的元素會以空字串值表示。

此方法可以對已選取個別表單控制項(例如 <input><textarea><select>)的 jQuery 物件進行操作。不過,通常選取 <form> 元素本身會比較容易進行序列化

1
2
3
4
$( "form" ).on( "submit", function( event ) {
console.log( $( this ).serializeArray() );
event.preventDefault();
} );

這會產生下列資料結構(假設瀏覽器支援 console.log

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
[
{
name: "a",
value: "1"
},
{
name: "b",
value: "2"
},
{
name: "c",
value: "3"
},
{
name: "d",
value: "4"
},
{
name: "e",
value: "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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>serializeArray demo</title>
<style>
body, select {
font-size: 14px;
}
form {
margin: 5px;
}
p {
color: red;
margin: 5px;
}
b {
color: blue;
}
</style>
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
</head>
<body>
<p><b>Results:</b> <span id="results"></span></p>
<form>
<select name="single">
<option>Single</option>
<option>Single2</option>
</select>
<select name="multiple" multiple="multiple">
<option selected="selected">Multiple</option>
<option>Multiple2</option>
<option selected="selected">Multiple3</option>
</select>
<br>
<input type="checkbox" name="check" value="check1" id="ch1">
<label for="ch1">check1</label>
<input type="checkbox" name="check" value="check2" checked="checked" id="ch2">
<label for="ch2">check2</label>
<input type="radio" name="radio" value="radio1" checked="checked" id="r1">
<label for="r1">radio1</label>
<input type="radio" name="radio" value="radio2" id="r2">
<label for="r2">radio2</label>
</form>
<script>
function showValues() {
var fields = $( ":input" ).serializeArray();
$( "#results" ).empty();
jQuery.each( fields, function( i, field ) {
$( "#results" ).append( field.value + " " );
} );
}
$( ":checkbox, :radio" ).on( "click", showValues );
$( "select" ).on( "change", showValues );
showValues();
</script>
</body>
</html>

示範