复选框已选中,未分配新值

时间:2012-07-02 16:51:16

标签: php

无论选择什么,它仍然为所有复选框分配值1,而不是将所选复选框更改为值0.以下是从语法角度来看正确的代码,但无论如何都默认为1我不明白为什么它没有将所选的框值更改为'0'

//Correct answer variables
$chkBox1 = '1';
$chkBox2 = '1';
$chkBox3 = '1';
$chkBox4 = '1';
$chkBox5 = '1';

if (isset($_POST['chkBox1'])) {

if ($chkBox1 == 'chkBox1Selected') {
$chkBox1 = '0';
}

}//End of chkBox1Selected logic


if (isset($_POST['chkBox2'])) {

if ($chkBox2 == 'chkBox2Selected') {
$chkBox2 = '0';
}

}//End of chkBox2Selected logic


if (isset($_POST['chkBox3'])) {

if ($chkBox3 == 'chkBox3Selected') {
$chkBox3 = '0';
}

}//End of chkBox3Selected logic

1 个答案:

答案 0 :(得分:4)

您的if语句永远不会评估为true

看一个复选框:

$chkBox1 = '1';

if (isset($_POST['chkBox1'])) {
    if ($chkBox1 == 'chkBox1Selected') {
        $chkBox1 = '0';
    }
}

$chkBox1设置为'1',并且永远不会更改,因此它永远不会等于'chkBox1Selected'

话虽如此,您不必担心复选框的价值,因为仅选中复选框将被发送到服务器

理论上,你可以这样做:

if (isset( $_POST['chkBox1'])) {
    $chkBox1 = '0';
}

但是,如果您想要阅读复选框的值,您应该可以这样做:

if (isset( $_POST['chkBox1'])) {
    if ($_POST['chkBox1'] == 'chkBox1Selected') {
        $chkBox1 = '0';
    }
}

或者,更简洁:

if( isset( $_POST['chkBox1']) && ($_POST['chkBox1'] == 'chkBox1Selected')) {
        $chkBox1 = '0';
}