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

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


当前回答

$('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);
        }
    })
});

其他回答

Ajax动作的例子是(':checked')使用jQuery而不是.val();

            var params = {
                books: $('input#users').is(':checked'),
                news : $('input#news').is(':checked'),
                magazine : $('input#magazine').is(':checked')
            };

参数将得到TRUE或FALSE的值。

我实际上会这样做。

有我的隐藏输入字段与复选框输入相同的名称

<input type="hidden" name="checkbox_name[]" value="0" />
<input type="checkbox" name="checkbox_name[]" value="1" />

然后当我post时,我首先删除在$_POST数组中拾取的重复值,然后显示每个唯一的值。

  $posted = array_unique($_POST['checkbox_name']);
  foreach($posted as $value){
    print $value;
  }

我从一个帖子中得到了这个,从数组中删除重复值

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

$('form').submit(function(event){
    $('input[type=checkbox]').prop('checked', function(index, value){
        return !value;
    });
});
$('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数组。

可能看起来很傻,但对我很管用。主要缺点是在视觉上是一个单选按钮,而不是一个复选框,但它不需要任何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;}

小提琴在这里

我想听到你在这段代码中发现的任何问题,因为我在生产中使用它