<form id="form">
<div>
<label>用户名:</label>
<input name="userName" type="text" />
</div>
<div>
<label>性别:</label>
<input name="sex" type="radio" value="1"/>男
<input name="sex" type="radio" value="0"/>女
</div>
<div>
<label>特长:</label>
<input name="speciality" type="checkbox" value="1"/>游泳
<input name="speciality" type="checkbox" value="2"/>篮球
<input name="speciality" type="checkbox" value="3"/>田径运动
</div>
<div>
<label>籍贯:</label>
<select name="province">
<option value="guangdong">广东</option>
<option value="beijing">北京</option>
<option value="shanghai">上海</option>
</select>
</div>
<div>
<label>备注:</label>
<textarea name="remark" rows="3"></textarea>
</div>
</form>
表单信息回填:
function handleFormInfo(obg) {
for (var key in obg) {
var value = obg[key];
$("form").find('[name="' + key + '"]').each(function (index, item) {
var tagName = $(this)[0].tagName;
var type = $(this).attr("type");
if (tagName == "INPUT") {
if (type == 'radio') {
$(this).attr('checked', $(this).val() == value);
} else if (type == 'checkbox') {
if (value) {
try {
arr = value.toString().split(',');
for (var i = 0; i < arr.length; i++) {
if ($(this).val() == arr[i]) {
$(this).attr('checked', true);
break;
}
}
} catch (error) {
console.log(key,value)
console.log(error)
}
}
} else {
$(this).val(value);
}
} else if (tagName == "SELECT") {
$(this).find("option").each(function (index, option) {
if ($(option)[0].value == value) {
$(option).attr("selected", true);
}
})
} else if (tagName == "TEXTAREA") {
$(this).val(value);
}
})
}
}
var obg = {
userName: "chenxiaohu",
sex: 1,
speciality: "2,3",
province: "guangdong",
remark: "remarktext"
}
handleFormInfo(obg)
获取表单数据的方式一:
var value = $('#form').serialize();
console.log('value : ',value );
// 输出:userName=chenxiaohu&sex=1&speciality=2&speciality=3&province=guangdong&remark=remarktext
获取表单数据的方式二:
let data = {
};
var value = $('#form').serializeArray();
$.each(value, function(index, item) {
//文本表单的值不为空才处理
if(item.value && $.trim(item.value) != "") {
if(!data[item.name]) {
data[item.name] = item.value;
} else {
//name属性相同的表单,值以英文,拼接
data[item.name] = data[item.name] + ',' + item.value;
}
}
});
console.log(JSON.stringify(data));