我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
当前回答
一句话解决方案:
$option1ChkBox = array_key_exists('chkBoxName', $_POST) ? true : false;
其他回答
我更喜欢整理$_POST
if (!$_POST['checkboxname']) !$_POST['checkboxname'] = 0;
它介意,如果POST没有checkboxname值,它是unchecked的,所以,给它赋一个值。
你可以为你的复选框值创建一个数组,并创建一个函数来检查值是否存在,如果不存在,它会介意是否未选中,你可以给值赋值
直接复制 美元(文档)。On ('change', "input[type=checkbox]", function () { var checkboxVal = (this.checked) ?1: 0; if (checkboxVal== 1) { (美元)。道具(“检查”,真正的); (美元).val(“true”); } 其他{ (美元)。道具(“检查”,假); (美元).val(“false”); } });
这是对之前答案的一种尝试,以自动保留具有特定值(在本例中为0)的未选中复选框,而不会在提交时选中所有复选框。
$("form").submit(function () {
let this_master = $(this);
// Remove any of the hidden values that may already be there (if the user previously canceled the submit)
this_master.find("*[id^='hiddenchkinput_']").remove();
// Get all unchecked checkboxes
this_master.find('input:checkbox:not(:checked)').each(function () {
let thisChk = $(this);
// Create a hidden input with the same name as the checkbox
let newInput = document.createElement('input');
$(newInput).attr('name', thisChk.attr('id'))
.attr('id', 'hiddenchkinput_' + thisChk.attr('id'))
.attr('type', 'hidden')
.val('0');
// Append the new input to the end of the form
this_master.append(newInput);
});
})
一句话解决方案:
$option1ChkBox = array_key_exists('chkBoxName', $_POST) ? true : false;
您不需要为所有复选框创建一个隐藏字段,只需复制我的代码。 它会改变复选框的值,如果不选中,值将赋值为0,如果选中复选框,则将值赋值为1
$("form").submit(function () {
var this_master = $(this);
this_master.find('input[type="checkbox"]').each( function () {
var checkbox_this = $(this);
if( checkbox_this.is(":checked") == true ) {
checkbox_this.attr('value','1');
} else {
checkbox_this.prop('checked',true);
//DONT' ITS JUST CHECK THE CHECKBOX TO SUBMIT FORM DATA
checkbox_this.attr('value','0');
}
})
})