HTML或php单选按钮奇怪的行为?

时间:2012-02-03 15:59:02

标签: php html radio-button

我正在做一些测试html / php表单。这里的一切都很好......但是单选按钮表现得很奇怪。以下是代码,下面将是奇怪行为的屏幕截图:

HTML

<!DOCTYPE html>
<html>
    <head>
    </head>

    <body>
        <h1>Differend sided dice</h1>
        <form action="dice.php" method="post">
        <input type="radio"   value="4" name="4side" checked  />4 side<br />
        <input type="radio"   value="10"name="10side" />10 side<br />
        <input type="radio"   value="20"name="20side" />20 side<br />
        <input type="submit" >
        </form>
    </body>
</html>

PHP

<html><head></head>
<body>
<?

    function rollOut($dice)  {
        $out = <<<HERE
        <p>You rolled <span style="color:red"> $dice </span> of the diec</p>
HERE;
        return $out;
        }

    function diceSide() {
        $dicetype = rand(1, 10); /* default */
        if ( isset($_POST["4side"] ) ) {
            $dicetype = rand(1, $_POST["4side"] );
            print rollOut($dicetype);
            }
        else if ( isset($_POST["10side"]) ) {
            $dicetype = rand(1, $_POST["10side"] );
            print rollOut($dicetype);
            }
        else if ( isset($_POST["20side"]) ) {
            $dicetype = rand(1, $_POST["20side"]); 
            print rollOut($dicetype);
            }
        else { 
        $dicetype = rand(1, 20);
        rollOut($dicetype);
        }
    }

    /* init main */
    diceSide(); 

    ?>
</body>
</html>

我将附加到屏幕截图上的奇怪之处: bug

所有按钮都像复选框一样?任何信息?

1 个答案:

答案 0 :(得分:8)

您必须为所有<input type='radio'>设置相同的名称,以便他们按预期行事

HTML code:

<!DOCTYPE html>
<html>
    <head>
    </head>

    <body>
        <h1>Differend sided dice</h1>
        <form action="dice.php" method="post">
        <input type="radio"   value="4" name="selectMe" checked  />4 side<br />
        <input type="radio"   value="10"name="selectMe" />10 side<br />
        <input type="radio"   value="20"name="selectMe" />20 side<br />
        <input type="submit" >
        </form>
    </body>
</html> 

PHP代码(我可以自由地简化它 - 应该像以前一样做,只需要更少的代码):

<html><head></head>
<body>
<?

    function rollOut($dice)  {
        $out = '<p>You rolled <span style="color:red"> '.$dice .'</span> of the diec</p>';
        return $out;
        }

    function diceSide() {
        $dicetype = rand(1, 10); /* default */

        if ( isset($_POST["selectMe"] ) ) {
            $dicetype = rand(1, $_POST["selectMe"]); 
            }
        print rollOut($dicetype);
    }
    /* init main */
    diceSide(); 

    ?>
</body>
</html>