我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
当前回答
为不同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;
}
}
其他回答
简单的答案。如果你的代码中有checked="checked"将其改为unchecked="unchecked"
所以你的文本应该是这样的:
输入类型=“复选框” 名称=“您选择的名称” 未选中=“未选中”
如果它不包含这个,你总是可以添加它
您还可以截取表单。提交事件和提交前的反向检查
$('form').submit(function(event){
$('input[type=checkbox]').prop('checked', function(index, value){
return !value;
});
});
可能看起来很傻,但对我很管用。主要缺点是在视觉上是一个单选按钮,而不是一个复选框,但它不需要任何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;}
小提琴在这里
我想听到你在这段代码中发现的任何问题,因为我在生产中使用它
为不同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;
}
}
Ajax动作的例子是(':checked')使用jQuery而不是.val();
var params = {
books: $('input#users').is(':checked'),
news : $('input#news').is(':checked'),
magazine : $('input#magazine').is(':checked')
};
参数将得到TRUE或FALSE的值。