我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
当前回答
可能看起来很傻,但对我很管用。主要缺点是在视觉上是一个单选按钮,而不是一个复选框,但它不需要任何javascript。
HTML
Initialy checked
<span><!-- set the check attribute for the one that represents the initial value-->
<input type="radio" name="a" value="1" checked>
<input type="radio" name="a" value="0">
</span>
<br/>
Initialy unchecked
<span><!-- set the check attribute for the one that represents the initial value-->
<input type="radio" name="b" value="1">
<input type="radio" name="b" value="0" checked>
</span>
和CSS
span input
{position: absolute; opacity: 0.99}
span input:checked
{z-index: -10;}
span input[value="0"]
{opacity: 0;}
小提琴在这里
我想听到你在这段代码中发现的任何问题,因为我在生产中使用它
其他回答
您可以在提交表单之前添加隐藏元素。
$('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));
}
})
});
<input type="checkbox" id="checkbox" name="field_name" value="1">
你可以在服务器端完成,不需要使用隐藏字段, 使用三元运算符:
isset($_POST['field_name']) ? $entity->attribute = $_POST['field_name'] : $entity->attribute = 0;
使用普通IF运算符:
if (isset($_POST['field_name'])) {
$entity->attribute = $_POST['field_name'];
} else {
$entity->attribute = 0;
}
当提交时复选框未选中时,将复选框的值更新为'NO'并设置checked = 'TRUE'
https://jsfiddle.net/pommyk/8d9jLrvo/26/
$(document).ready(function()
{
function save()
{
if (document.getElementById('AgeVerification').checked == false)
{
document.getElementById('AgeVerification').value = 'no';
document.getElementById('AgeVerification').checked = true;
}
}
document.getElementById("submit").onclick = save;
})
function SubmitCheckBox(obj) {
obj.value = obj.checked ? "on" : "off";
obj.checked = true;
return obj.form.submit();
}
<input type=checkbox name="foo" onChange="return SubmitCheckBox(this);">
你可以在表单的提交事件中执行一些Javascript。这就是你所能做的,没有办法让浏览器自己做这件事。这也意味着没有Javascript的用户将无法使用表单。 更好的方法是在服务器上知道有哪些复选框,这样就可以推断出那些从提交的表单值(PHP中的$_POST)中缺少的复选框是未选中的。