描述: 将用作提交的表单元素的值编译成拥有name和value对象组成的数组。例如[ { name: a value: 1 }, { name: b value: 2 },…]
-
添加的版本: 1.2.serializeArray()
.serializeArray()
方法创建一个对象组成的javascript数组,用来编码成一个JSON一样的字符串。 它可以对一个代表一组表单元素的 jQuery 对象进行操作。表单元素可以有以下几种类型:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<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>
<textarea name="d" rows="8" cols="40">4</textarea>
<option value="5" selected="selected">5</option>
<option value="6">6</option>
<option value="7">7</option>
<input type="checkbox" name="f" value="8" id="f" />
<input type="submit" name="g" value="Submit" id="g" />
|
.serializeArray()
方法使用标准的W3C”successful controls”的标准来检测哪些元素应当包括在内。被禁用的元素不会被包括在内。并且,元素必须含有 name
属性。此外,提交按钮的值也不会被序列化。文件选择元素的数据也不会被序列化。
.serializeArray()
方法可以对单独选择的表单元素对象进行操作, 比如 <input>
, <textarea>
, 和 <select>
。还有个更方便的方法是,直接使用 <form>
标签来进行序列化操作:
1
2
3
4
|
$('form').submit(function() {
console.log($(this).serializeArray());
|
这将产生以下数据结构(浏览器提供的console.log
):
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
body, select { font-size:14px; }
p { color:red; margin:5px; }
<script src="https://code.jquery.com/jquery-latest.js"></script>
<p><b>Results:</b> <span id="results"></span></p>
<select name="multiple" multiple="multiple">
<option selected="selected">Multiple</option>
<option>Multiple2</option>
<option selected="selected">Multiple3</option>
<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>
var fields = $(":input").serializeArray();
jQuery.each(fields, function(i, field){
$("#results").append(field.value + " ");
$(":checkbox, :radio").click(showValues);
$("select").change(showValues);
|
转载请注明:悠然品鉴 » jQuery .serializeArray() 用法 手册 | 示例代码