网上很多解决方案,我这种应该还算简单的
只需要给checkbox元素添加data-default-value="0"
表示未选中的默认值
直接使用版
<input class="form-check-input" name="top" value="1" data-default-value="0" type="checkbox" role="switch" id="top">
let data = $('.form2').serialize(); var $notchecked_obj = $('.form2 input[type=checkbox]:not(:checked)'); $notchecked_obj.each(function (index, element) { let value = $(element).attr('data-default-value'); let key = $(element).attr('name'); data += '&' + $.param({[key]: value}); }); alert(data);
稍微封装版,放公共函数里面,以后可以直接用
function formcheck(form_selector_str, serialize_data) { // 组装选择器 let selector = form_selector_str + ' input[type=checkbox]:not(:checked)'; //遍历没有选中的checkbox let $notchecked_obj = $(selector); // console.log($notchecked_obj); let temp = serialize_data; $notchecked_obj.each(function (index, element) { let value = $(element).attr('data-default-value'); let key = $(element).attr('name'); temp += '&' + $.param({[key]: value}); }); return temp; } var res = formcheck('.form2', $('.form2').serialize());