如果在表单提交时勾选复选框输入值数据,浏览器是否仅发送复选框输入值数据是标准行为?

如果没有提供值数据,默认值是否总是“on”?

假设上述假设是正确的,那么所有浏览器的这种行为是否一致呢?


当前回答

输入类型="hidden" name="is_main" value="0"

输入类型="checkbox" name="is_main" value="1"

所以你可以像我在应用程序中那样控制。 如果检查成功,则发送值1,否则为0

其他回答

当且仅当复选框被选中时,复选框将发布值“on”。您可以使用隐藏输入,而不是捕获复选框值

JS:

var chk = $('input[type="checkbox"]');
    chk.each(function(){
        var v = $(this).attr('checked') == 'checked'?1:0;
        $(this).after('<input type="hidden" name="'+$(this).attr('rel')+'" value="'+v+'" />');
    });

chk.change(function(){ 
        var v = $(this).is(':checked')?1:0;
        $(this).next('input[type="hidden"]').val(v);
    });

HTML:

<label>Active</label><input rel="active" type="checkbox" />

Just like ASP.NET variant, except put the hidden input with the same name before the actual checkbox (of the same name). Only last values will be sent. This way if a box is checked then its name and value "on" is sent, whereas if it's unchecked then the name of the corresponding hidden input and whatever value you might like to give it will be sent. In the end you will get the $_POST array to read, with all checked and unchecked elements in it, "on" and "false" values, no duplicate keys. Easy to process in PHP.

以上答案没有一个让我满意。 我发现最好的解决方案是在每个具有相同名称的复选框输入之前包含一个隐藏输入。

<输入类型=“隐藏”

<input type=“checkbox” name=“foo[]”/>

然后在服务器端,使用一个小算法可以得到更像HTML应该提供的东西。

function checkboxHack(array $checkbox_input): array
{
    $foo = [];
    foreach($checkbox_input as $value) {
        if($value === 'on') {
            array_pop($foo);
        }
        $foo[] = $value;
    }
    return $foo;
}

这将是原始输入

array (
    0 => 'off',
    1 => 'on',
    2 => 'off',
    3 => 'off',
    4 => 'on',
    5 => 'off',
    6 => 'on',
),

函数会返回

array (
    0 => 'on',
    1 => 'off',
    2 => 'on',
    3 => 'on',
)  

如果未选中复选框,则它不会在表单提交时发送数据。

HTML5第4.10.22.4节构造表单数据集描述了表单数据的构造方式:

如果满足以下任何条件,则跳过这些子步骤 对于这个元素: […] 字段元素是一个输入元素,其类型为 属性处于复选框状态,其选中度为false。

如果value缺失,则指定默认值on:

否则,如果字段元素是一个输入元素,其类型属性处于复选框状态或单选按钮状态,则运行这些进一步嵌套的子步骤: 如果字段元素指定了value属性,则让value为该属性的值;否则,让value为字符串“on”。

因此在表单数据构造过程中会跳过未选中的复选框。

HTML4中也要求类似的行为。期望所有兼容的浏览器都有这种行为是合理的。

浏览器只发送复选框输入是标准行为吗 价值数据是否在表单提交时进行检查?

是的,因为否则就没有可靠的方法来确定复选框是否被选中(如果它改变了值,则可能存在这样的情况,即当您选中的期望值与它被交换到的值相同时)。

如果没有提供值数据,默认值是否总是“on”?

其他答案证实“开”是默认值。但是,如果你对值不感兴趣,可以使用:

if (isset($_POST['the_checkbox'])){
    // name="the_checkbox" is checked
}