如何使用jQuery序列化那些数组输入
<form id="myform" action="" method="">
<input type="text" name="name[0].basketball">
<input type="text" name="name[0].ball">
<input type="text" name="name[1].basketball">
<input type="text" name="name[1].ball">
</form>
看起来像这样:
[{basketball: 'TestBasketball', Ball: 'TestBall'}, {basketball: 'TestBasketball1', Ball: 'TestBall2'}]
jQuery(此代码不起作用,仅获得名称[0] .basketball:“ TestBasketball”)
$('#myform').serializeArray();
最佳答案
像这样吗
var ser = [];
$("#myform>input[type=text]").each(function() {
var idx = parseInt(this.name.split("[")[1]);
var key = this.name.split(".")[1];
if (ser[idx]) ser[idx][key]=this.value;
else ser.push({[key]:this.value});
});
console.log(ser);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform" action="" method="">
<input type="text" name="name[0].basketball" value="TestBasketball1" />
<input type="text" name="name[0].ball" value="TestBall1" />
<input type="text" name="name[1].basketball" value="TestBasketball2">
<input type="text" name="name[1].ball" value="TestBall2" />
</form>