How get value for unchecked checkbox in checkbox elements when form posted?

前端 未结 11 2384
独厮守ぢ
独厮守ぢ 2020-11-27 17:13

I have a form like below :

相关标签:
11条回答
  • 2020-11-27 17:25

    Assuming we are using checkboxes with zeros or ones...

    Using a hidden checkbox with a zero value is just a work-around. Another work around would be to add 0 to the value when receiving the post or get.

    Example:

    $chkbx1 = $_POST['chckbx1']; $chkbx1 += 0;

    This takes a NULL value an turns it into a zero, but if the value is one, as in its checked, then the value stays the same.

    The real issue here isn't inventing a work-around. Its understanding why this is happening. Older versions of mySQL takes null values and converts them into a zero. In newer versions, you must disable strict mode and then a work-around is not needed.

    0 讨论(0)
  • 2020-11-27 17:26

    Why have you taken it in an array? You can get the unchecked box as 0 by using "isset"

        if(!isset($_POST['status_2'])
        {
          //Set status_2 parameter as 0
        }
    
    0 讨论(0)
  • 2020-11-27 17:29

    the question may already be answered but i just wanted to take a stab at it...server side only solution:

    $p = $_POST;
    $a = array();
    $a['status_3'] = (int) ($p['status_3'] === 1);
    $a['status_2'] = (int) ($p['status_2'] === 1);
    $a['status_1'] = (int) ($p['status_1'] === 1);
    

    Testing

     // if input is Array("status_1"=>1) output will be
     Array ( [status_1] => 1 [status_3] => 0 [status_2] => 0 )
    
     // if input is Array("status_1"=>1, "status_2"=>1) output will be
     Array ( [status_1] => 1 [status_3] => 0 [status_2] => 1)
    
    0 讨论(0)
  • 2020-11-27 17:30

    I thinks it impossible to get array like what you want from html forms. But this some tricks can be used:

    $defaultForm = array(
    'status_1' => 0,
    'status_2' => 0,
    'status_3' => 0, 
    );
    
    // example array from $_POST
    $form = array(
    'status_1' => 1,
    'status_3' => 1, 
    );
    
    $form = array_merge($defaultForm, $form);
    

    Result:

    array(3) {

    'status_1' => int(1)
    'status_2' => int(0)
    'status_3' => int(1)

    }

    0 讨论(0)
  • 2020-11-27 17:32

    Try this one:

    for ($i = 1; $i<=3; $i++) {
        $_POST["status_$i"] = isset($_POST["status_$i"]) ? $_POST["status_$i"] : 0; // 0 if not set
    }
    
    var_dump($_POST);
    
    0 讨论(0)
  • 2020-11-27 17:35

    I think adding hidden fields like this will work

    <input type="hidden" id="status_1_" name="status_1"  value="0">
    <input type="checkbox" id="status_1" name="status_1" value="1" />
    
    <input type="hidden" id="status_2_" name="status_2" value="0">
    <input type="checkbox" id="status_2" name="status_2" value="1" />
    
    <input type="hidden" id="status_3_" name="status_3" value="0">
    <input type="checkbox" id="status_3" name="status_3" value="1" />
    
    0 讨论(0)
提交回复
热议问题