使用PHP或jQuery设置Bootstrap-Switch复选框选中状态

时间:2017-04-13 11:23:07

标签: php jquery twitter-bootstrap bootstrap-switch

我需要根据mysql数据库中的值使用bootstrap-switch设置复选框的状态。

我正在尝试使用PHP这样做,但它似乎不起作用,代码是摘录:

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>';
}

交换机检查状态似乎是随机的,而不是基于我从数据库接收的值。

1 个答案:

答案 0 :(得分:0)

代码似乎很好我只是将比较运算符修复为===以确定类型。

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>';
}

如果$row["devicestatus"]中没有任何奇怪的状态,您甚至可以使用ternary operator

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