Ilian Zapryanov
Ilian Zapryanov

Reputation: 1185

HTML or php radio button strange behaviour?

I was making a little test html/php form. Everything is fine here... but the radio buttons are acting strange. Here is the code and below will be a screenshot of the weird behaviour:

The 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>

The 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>

And the weird thing I`ll attach to a screenshot: bug

All buttons act like checkboxes??? Any info?

Upvotes: 1

Views: 374

Answers (1)

Bogdan
Bogdan

Reputation: 865

you have to set the same name for all <input type='radio'> for them to act as expected

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 code (i took the freedom of simplifying it a bit --should do the same thing as before, just less code):

<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>

Upvotes: 8

Related Questions