Search code examples
phpjquerytwitter-bootstrapbootstrap-switch

Setting Bootstrap-Switch checkbox checked state with PHP or jQuery


I need to set the state of a checkbox using bootstrap-switch based on values from a mysql database.

I am trying to do it with PHP like this but it doesn't seem to work, the code is an excerpt:

while ($row = $result->fetch_assoc()) {

    $checkdevicestate = $row["devicestatus"];
    if ($checkdevicestate == "false") {
        $devstatus = "";
    } else if ($checkdevicestate == "true") {
        $devicestatus = "checked";
    }   

    $devicecontent .= '<tr><td style="width:60%"><span data-icon="7" class="linea-icon linea-basic fa-fw"></span>'. $row["devicename"] .'</td><td style="width:100%"><input type="checkbox" id="' . $row["devicecode"].'" '.$devicestatus.' class="devicebtn"data-on-color="info" data-size="small"data-off-color="danger"></td></tr>';
}

The switch check-state seems random and not based on the values I am receiving from the DB.


Solution

  • The code seems fine I would just fix the comparison operator to === to be sure about the type.

    while ($row = $result->fetch_assoc()) {
        $checkdevicestate = $row["devicestatus"];
        if ($checkdevicestate === "false") {
            $devstatus = "";
        } else if ($checkdevicestate === "true") {
            $devicestatus = "checked";
        }   
    
        $devicecontent .= '<tr><td style="width:60%"><span data-icon="7" class="linea-icon linea-basic fa-fw"></span>'. $row["devicename"] .'</td><td style="width:100%"><input type="checkbox" id="' . $row["devicecode"].'" '.$devicestatus.' class="devicebtn"data-on-color="info" data-size="small"data-off-color="danger"></td></tr>';
    }
    

    If you don't have any strange state in $row["devicestatus"] you can even just use a ternary operator.

    $devicestatus = ($checkdevicestate === "true") ? "checked='checked'" : '';