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

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


当前回答

“我采用了服务器方法。似乎工作得很好-谢谢。- reach4lasasers 12月1日'09 at 15:19“我想从所有者那里推荐它。引用:javascript解决方案取决于服务器处理程序(我没有检查它)

if(!isset($_POST["checkbox"]) or empty($_POST["checkbox"])) $_POST["checkbox"]="something";

其他回答

这是对之前答案的一种尝试,以自动保留具有特定值(在本例中为0)的未选中复选框,而不会在提交时选中所有复选框。

$("form").submit(function () {
    let this_master = $(this);

    // Remove any of the hidden values that may already be there (if the user previously canceled the submit)
    this_master.find("*[id^='hiddenchkinput_']").remove();

    // Get all unchecked checkboxes
    this_master.find('input:checkbox:not(:checked)').each(function () {
      let thisChk = $(this);

      // Create a hidden input with the same name as the checkbox
      let newInput = document.createElement('input');
      $(newInput).attr('name', thisChk.attr('id'))
        .attr('id', 'hiddenchkinput_' + thisChk.attr('id'))
        .attr('type', 'hidden')
        .val('0');
      // Append the new input to the end of the form
      this_master.append(newInput);
    });
})

我知道这个问题已经提出3年了,但我找到了一个我认为非常有效的解决方案。

您可以检查$_POST变量是否已赋值,并将其保存在变量中。

$value = isset($_POST['checkboxname'] ? 'YES' : 'NO';

isset()函数检查$_POST变量是否被赋值。按照逻辑,如果它没有被分配,那么复选框就不会被选中。

@cpburnz说对了,但是代码太多了,下面是使用更少代码的相同想法:

JS:

// jQuery OnLoad
$(function(){
    // Listen to input type checkbox on change event
    $("input[type=checkbox]").change(function(){
        $(this).parent().find('input[type=hidden]').val((this.checked)?1:0);
    });
});

HTML(注意字段名使用数组名):

<div>
    <input type="checkbox" checked="checked">
    <input type="hidden" name="field_name[34]" value="1"/>
</div>
<div>
    <input type="checkbox">
    <input type="hidden" name="field_name[35]" value="0"/>
</div>
<div>

对于PHP:

<div>
    <input type="checkbox"<?=($boolean)?' checked="checked"':''?>>
    <input type="hidden" name="field_name[<?=$item_id?>]" value="<?=($boolean)?1:0?>"/>
</div>

直接复制 美元(文档)。On ('change', "input[type=checkbox]", function () { var checkboxVal = (this.checked) ?1: 0; if (checkboxVal== 1) { (美元)。道具(“检查”,真正的); (美元).val(“true”); } 其他{ (美元)。道具(“检查”,假); (美元).val(“false”); } });

您可以在提交表单之前添加隐藏元素。

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