.serializeArray()
.serializeArray() 返回: Array
面熟: 将用作提交的表单元素的值编译成拥有name和value对象组成的数组。例如[ { name: a value: 1 }, { name: b value: 2 },...]
version added: 1.2.serializeArray()
.serializeArray() 方法创建一个对象组成的javascript数组,用来编码成一个JSON一样的字符串。 这是数组使用jQuery对象代表一组表单元素的构成。 这个表单元素可以的几种类型:
<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>
The .serializeArray() 方法可以操作一个jQuery对象已选定的表单元素个体, 比如 <input>, <textarea>, 和 <select>。无论如何他能非常简单系列化:选择的 <form> 标签:
$('form').submit(function() {
$.print($(this).serializeArray());
return false;
});
这产生下列数据结构:
[
{
name: a
value: 1
},
{
name: b
value: 2
},
{
name: c
value: 3
},
{
name: d
value: 4
},
{
name: e
value: 5
}
]
举例:
从表单获取值,遍历并且显示他们
<!DOCTYPE html>
<html>
<head>
<style>
body, select { font-size:14px; }
form { margin:5px; }
p { color:red; margin:5px; }
b { color:blue; }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.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").click(showValues);
$("select").change(showValues);
showValues();
</script>
</body>
</html>