我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。

是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?


当前回答

最简单的解决方案是一个“虚拟”复选框加上隐藏输入,如果你正在使用jquery:

 <input id="id" type="hidden" name="name" value="1/0">
 <input onchange="$('#id').val(this.checked?1:0)" type="checkbox" id="dummy-id" 
 name="dummy-name" value="1/0" checked="checked/blank">

将两个输入的值设置为当前的1/0值,如果为1,则checked=checked。输入字段(活动)现在将始终被发布为1或0。此外,复选框可以在提交前点击多次,仍然可以正常工作。

其他回答

$('form').submit(function () {
    $(this).find('input[type="checkbox"]').each( function () {
        var checkbox = $(this);
        if( checkbox.is(':checked')) {
            checkbox.attr('value','1');
        } else {
            checkbox.after().append(checkbox.clone().attr({type:'hidden', value:0}));
            checkbox.prop('disabled', true);
        }
    })
});

我的做法有点不同。首先,我更改了所有未选中复选框的值。到“0”,然后全部选中,因此该值将被提交。

函数checkboxvalues () { $ (" # checkbox-container输入:复选框"). each函数({ if ($ () .prop(“检查”)! = true) { (美元).val(“0”); (美元)。道具(“检查”,真正的); } }); }

到目前为止,我最喜欢的解决方案是放置一个与可能不被选中的复选框同名的隐藏输入。我认为它的工作原理是,如果复选框没有被选中,隐藏输入仍然是成功的,并发送到服务器,但如果复选框被选中,它将覆盖之前的隐藏输入。这样,您就不必跟踪已发布数据中的哪些值应该来自复选框。

<form>
  <input type='hidden' value='0' name='selfdestruct'>
  <input type='checkbox' value='1' name='selfdestruct'>
</form>

您还可以截取表单。提交事件和提交前的反向检查

$('form').submit(function(event){
    $('input[type=checkbox]').prop('checked', function(index, value){
        return !value;
    });
});

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
)