how do I get all checkbox variables even if not checked from HTML to PHP?

前端 未结 5 1129
被撕碎了的回忆
被撕碎了的回忆 2020-12-02 17:39

I noticed that PHP seems to return only values of checked checkboxes. I would like to see a list of checkboxes, not just values of checked checkboxes. Is there a way to dete

相关标签:
5条回答
  • This isn't something that can be done purely in PHP.

    Browsers only send information about checkboxes if they are checked, if you want to also send information about unchecked checkboxes, you'll have to add hidden fields in the form and use javascript to manage them.

    0 讨论(0)
  • 2020-12-02 18:02

    I just stumbled across this problem myself and I sorted it by updating all values in the database to unchecked then re-checking only the ones that are in the POST data, this works fine for me but might not be everyone's cup of tea.

    0 讨论(0)
  • 2020-12-02 18:06

    I just ran into this problem myself. I solved it by adding a duplicate hidden field with the same name. When the browser sends this information, the second field overrides the first (so ensure that the hidden field comes first).

    <input type="hidden" name="foo" value="">
    <input type="checkbox" name="foo" value="bar">
    

    If the checkbox is not checked you get:

    $_REQUEST[ 'foo' ] == ""
    

    If the checkbox is checked you get:

    $_REQUEST[ 'foo' ] == "bar"
    
    0 讨论(0)
  • 2020-12-02 18:06

    Suppose you have a 3 checkboxes you want to check, and update_settings is the name of your functions that take the checkbox name as a first argument and a bool value as a second one (activate or not).

    Take the following snippet:

    $checkboxes = array("checkbox1", "checkbox2", "checkbox3");
    foreach($checkboxes as $checkbox){
        $checked = isset($_POST[$checkbox]);
        update_settings($checkbox, $checked);
    }
    

    Althouth Peter Kovacs solution it's going to work, I don't think it's practical since you can already check your variables using isset.

    0 讨论(0)
  • 2020-12-02 18:17

    A pure PHP implementation doesn't seem possible, you can try using jQuery/AJAX though.

    0 讨论(0)
提交回复
热议问题