我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
当前回答
这是对之前答案的一种尝试,以自动保留具有特定值(在本例中为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);
});
})
其他回答
我的做法有点不同。首先,我更改了所有未选中复选框的值。到“0”,然后全部选中,因此该值将被提交。
函数checkboxvalues () { $ (" # checkbox-container输入:复选框"). each函数({ if ($ () .prop(“检查”)! = true) { (美元).val(“0”); (美元)。道具(“检查”,真正的); } }); }
一句话解决方案:
$option1ChkBox = array_key_exists('chkBoxName', $_POST) ? true : false;
$('input[type=checkbox]').on("change",function(){
var target = $(this).parent().find('input[type=hidden]').val();
if(target == 0)
{
target = 1;
}
else
{
target = 0;
}
$(this).parent().find('input[type=hidden]').val(target);
});
<p>
<input type="checkbox" />
<input type="hidden" name="test_checkbox[]" value="0" />
</p>
<p>
<input type="checkbox" />
<input type="hidden" name="test_checkbox[]" value="0" />
</p>
<p>
<input type="checkbox" />
<input type="hidden" name="test_checkbox[]" value="0" />
</p>
如果省略复选框的名称,则不会通过。 只有test_checkbox数组。
Ajax动作的例子是(':checked')使用jQuery而不是.val();
var params = {
books: $('input#users').is(':checked'),
news : $('input#news').is(':checked'),
magazine : $('input#magazine').is(':checked')
};
参数将得到TRUE或FALSE的值。
“我有一大堆默认选中的复选框”——这就是我解决问题的方法:
if(($C1)OR($C2)OR... ($C18)){echo "some are checked!";} else{$C1='set';$C2='set';$C3='set';$C4='set';$C5='set';$C6='set';$C7='set';$C8='set';$C9='set';$C10='set';$C11='set';$C12='set';$C13='set';$C14='set';$C15='set';$C16='set';$C17='set';$C18='set';} //(if all are unchecked - set them to 'check' since its your default) the above line will execute the echo if some are unchecked but the checked ones will still have the value parameter set therefore, to keep them set, when writing them in the form, use if($C1){echo "checked";} use the values in the further logic...
! !这种方法的局限性:你不能取消选中所有的东西——它们都会被重新选中