原文链接:https://blog.csdn.net/qq_27579471/article/details/102528337
问题:layui的form中,选中多个checkbox复选框(name都相同)时,data.field中只会有最后一个选中的checkbox的值!
<form class="layui-form" action=""> <div class="layui-form-item"> <label class="layui-form-label">复选框</label> <div class="layui-input-block"> <input type="checkbox" name="like" title="写作"> <input type="checkbox" name="like" title="阅读"> <input type="checkbox" name="like" title="发呆"> </div> </div> <div class="layui-form-item"> <div class="layui-input-block"> <button class="layui-btn" lay-submit lay-filter="formDemo">立即提交</button> <button type="reset" class="layui-btn layui-btn-primary">重置</button> </div> </div> </form>
<script> //Demo layui.use('form', function(){ var form = layui.form; //监听提交 form.on('submit(formDemo)', function(data){ layer.msg(JSON.stringify(data.field)); return false; }); }); </script>
解决方法:
1.layui提交checkbox复选框多个值的时候只会提交最后一个的值,故需要手动处理,要么拼接成字符串传到后台用字符串接收后再切割成数组,要么组装成js数组传到后台直接用数组接收;
2.ajax提交数组到后台,需要设置参数traditional: true。
//获取checkbox数据,组装成数组!!!!!! var like=[]; $('input[name="like"]:checked').each(function(index, domEle){
like.push($(this).val());
});
data.field.noRepeatUploadBanks = noRepeatUploadBanks;
layui.use('form', function(){
var form = layui.form;
form.on('submit(submit)', function(data){
//console.log(data.field) //当前容器的全部表单字段,名值对形式:{name: "value"}
//获取checkbox数据,组装成数组!!!!!!
var noRepeatUploadBanks =[];
$('input[name="noRepeatUploadBanks"]:checked').each(function(index, domEle){
noRepeatUploadBanks.push($(this).val());
});
data.field.noRepeatUploadBanks = noRepeatUploadBanks;
var url="${pageContext.request.contextPath}/admin/doEditSysSetting";
layer.confirm('您确认保存设置吗', {icon: 3, title:'提示'}, function(index){
layer.close(index);//关闭询问弹框
$.ajax({
type: "POST",
url: url,
data: data.field,
traditional: true, //是否使用传统的方式浅层序列化,若有数组参数或对象参数需要设置true!!!!!!
dataType:"json",
success: function(returnData){
if(returnData.code==1){
//修改隐藏input[oldCrontabStatusInt]的值
var new_oldCrontabStatusInt = returnData.obj;
$('input[name=oldCrontabStatusInt]').val(new_oldCrontabStatusInt);
layer.msg('保存成功', {
icon: 1,
time: 20000, //20s后自动关闭
btn: ['确定']
}, function(){
parent.layer.closeAll();
});
}else{
layer.msg(returnData.msg, {icon: 2});
}
}
});
});
return false; //阻止表单跳转。如果需要表单跳转,去掉这段即可。
});
});