How to retrieve unchecked checkbox values with PHP

-1

I need to identify fields in checkbox that are unmarked via PHP

    
asked by anonymous 18.09.2016 / 00:08

1 answer

1

simple, mount a ternary:

$checboxName = isset($_POST['name'])?true:false;

If it exists then it has been set, if not.

EDIT

If you have too many checkboxs and you do not want to see all of them via ternary, you should event in javascript to set value and input before it is sent.

<?php
echo '<pre>';
var_dump($_POST);
echo '</pre>';
?>

<form method="post" id="form">
    <input type="checkbox" name="name">
    <input type="submit" value="send">
</form>

<script type="text/javascript">
    document.getElementById('form').addEventListener('submit', function(){ // CRIA EM EVENTO QUE É DISPARADO QUANDO O ELEMENTO DE ID 'form' FOR 'submetido/enviado'.
        var inputs = this.getElementsByTagName('input'); // PEGA TODOS OS INPUTS PRESENTES NESSE ELEMENTO
        for(var i in inputs){ // ITERA OS INPUTS
            var input = inputs[i];
            if(input.type == 'checkbox'){ // CASO SEJA UM 'checkbox'
                input.value = input.checked; // SETA 'value' COM TRUE/FALSE DE ACORDO COM O CHECKED
            }
            input.checked = true; // SETA COMO CHECKED PARA QUE ELE SEJA ENVIADO, O VALOR VALIDO É O QUE ESTA NO 'value' DO ELEMENTO
        }
    });
</script>

Problems

  • This method generates a bad visual effect, because when sending the form all checked are marked, even if they are not true, to solve this you can use ajax.
  • PHP captures the value of $_POST as a string. So even sent true / false, this will be string. To solve this problem you can use this function.

Check String true / false

function is_true($var){
    if(is_string($var)){
        if(preg_match('~^(false|f)$~', $var) != null){
            return false;
        }
    }
    return !!$var;
}
    
18.09.2016 / 00:24