Do checkbox inputs only post data if they're checked?

后端 未结 12 892
盖世英雄少女心
盖世英雄少女心 2020-11-22 08:04

Is it standard behaviour for browsers to only send the checkbox input value data if it is checked upon form submission?

And if no value data is supplied, is the defa

12条回答
  •  时光取名叫无心
    2020-11-22 08:36

    None of the above answers satisfied me. I found the best solution is to include a hidden input before each checkbox input with the same name.

    Then on the server side, using a little algorithm you can get something more like HTML should provide.

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

    This will be the raw input

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

    And the function will return

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

提交回复
热议问题