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

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


当前回答

这是对之前答案的一种尝试,以自动保留具有特定值(在本例中为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);
    });
})

其他回答

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

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

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

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

我个人最喜欢的是添加一个具有相同名称的隐藏字段,如果复选框未选中,将使用该字段。但解决方案并不像看起来那么容易。

如果你添加以下代码:

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

浏览器不会真正关心您在这里做了什么。浏览器将把两个参数都发送给服务器,服务器必须决定如何处理它们。

例如,PHP将最后一个值作为要使用的值(参见:重复HTTP GET查询键的权威位置)

但是我使用过的其他系统(基于Java)是这样做的——它们只提供第一个值。 .NET会给你一个包含这两个元素的数组

我会试着在某个时候用node.js, Python和Perl测试这个。

我用JavaScript解决了这个问题:

<input type="hidden" name="checkboxName" value="0"><input type="checkbox" onclick="this.previousSibling.value=1-this.previousSibling.value">

注意在这两个输入元素之间不要有任何空格或换行符!

你可以使用this.previousSibling.previousSibling来获取“上层”元素。

使用PHP,您可以检查命名隐藏字段为0(未设置)或1(设置)。

我更喜欢整理$_POST

if (!$_POST['checkboxname']) !$_POST['checkboxname'] = 0;

它介意,如果POST没有checkboxname值,它是unchecked的,所以,给它赋一个值。

你可以为你的复选框值创建一个数组,并创建一个函数来检查值是否存在,如果不存在,它会介意是否未选中,你可以给值赋值