我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
当前回答
我知道这个问题已经提出3年了,但我找到了一个我认为非常有效的解决方案。
您可以检查$_POST变量是否已赋值,并将其保存在变量中。
$value = isset($_POST['checkboxname'] ? 'YES' : 'NO';
isset()函数检查$_POST变量是否被赋值。按照逻辑,如果它没有被分配,那么复选框就不会被选中。
其他回答
直接复制 美元(文档)。On ('change', "input[type=checkbox]", function () { var checkboxVal = (this.checked) ?1: 0; if (checkboxVal== 1) { (美元)。道具(“检查”,真正的); (美元).val(“true”); } 其他{ (美元)。道具(“检查”,假); (美元).val(“false”); } });
我个人最喜欢的是添加一个具有相同名称的隐藏字段,如果复选框未选中,将使用该字段。但解决方案并不像看起来那么容易。
如果你添加以下代码:
<form>
<input type='hidden' value='0' name='selfdestruct'>
<input type='checkbox' value='1' name='selfdestruct'>
</form>
浏览器不会真正关心您在这里做了什么。浏览器将把两个参数都发送给服务器,服务器必须决定如何处理它们。
例如,PHP将最后一个值作为要使用的值(参见:重复HTTP GET查询键的权威位置)
但是我使用过的其他系统(基于Java)是这样做的——它们只提供第一个值。 .NET会给你一个包含这两个元素的数组
我会试着在某个时候用node.js, Python和Perl测试这个。
为不同ID的复选框添加一个隐藏输入:
<input id='testName' type='checkbox' value='Yes' name='testName'>
<input id='testNameHidden' type='hidden' value='No' name='testName'>
在提交表单之前,根据检查的条件禁用隐藏输入:
form.addEventListener('submit', () => {
if(document.getElementById("testName").checked) {
document.getElementById('testNameHidden').disabled = true;
}
}
您可以在提交表单之前添加隐藏元素。
$('form').submit(function() {
$(this).find('input[type=checkbox]').each(function (i, el) {
if(!el.checked) {
var hidden_el = $(el).clone();
hidden_el[0].checked = true;
hidden_el[0].value = '0';
hidden_el[0].type = 'hidden'
hidden_el.insertAfter($(el));
}
})
});
I see this question is old and has so many answers, but I'll give my penny anyway. My vote is for the javascript solution on the form's 'submit' event, as some has pointed out. No doubling the inputs (especially if you have long names and attributes with php code mixed with html), no server side bother (that would require to know all field names and to check them down one by one), just fetch all the unchecked items, assign them a 0 value (or whatever you need to indicate a 'not checked' status) and then change their attribute 'checked' to true
$('form').submit(function(e){
var b = $("input:checkbox:not(:checked)");
$(b).each(function () {
$(this).val(0); //Set whatever value you need for 'not checked'
$(this).attr("checked", true);
});
return true;
});
这样你会得到一个像这样的$_POST数组:
Array
(
[field1] => 1
[field2] => 0
)