Skip to content
Advertisement

How to create drop-down lists and randomly show one of the items chosen?

There are 4 text boxes existing in the piece of code below. You can type everything you want within these four text boxes and when you click the “Pick one” button, you will get back the text you’ve entered within the text boxes. But I would like to change these text boxes to drop-down lists from which you can select four different teams and when you click the “Pick one” button, randomly, you will get one of the four teams you’ve chosen.

<?php

error_reporting(0);

if(isset($_POST['submit']))
    {
        $team1=$_POST['team1'];
        $team2=$_POST['team2'];
        $team3=$_POST['team3'];
        $team4=$_POST['team4'];

        $teams=array
        (
            "1" =>"$team1",
            "2" =>"$team2",
            "3" =>"$team3",
            "4" =>"$team4",
        );
    $random = rand(1, 4);
    }
?>


<html>
<form action="index.php" method="POST">
Enter the team name<input type="text" name="team1" value="<?php echo $team1 ?>"><br>
Enter the team name<input type="text" name="team2" value="<?php echo $team2 ?>"><br>
Enter the team name<input type="text" name="team3" value="<?php echo $team3 ?>"><br>
Enter the team name<input type="text" name="team4" value="<?php echo $team4 ?>"><p>

<input type="submit" name="submit" value="Pick One!"><br>
</form>

<?php

print $teams["$random"];

?>
</html>

Advertisement

Answer

If you want use drop-down lists instead of text boxes, you can use the piece of code below:

<!DOCTYPE html>
<html>
<body>

    <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post">

        <label for="select1">Team 1: </label>
        <select name="team1" id="select1">
            <option>TeamName1</option>
            <option>TeamName2</option>
            ...
        </select><br/>

        <label for="select2">Team 2: </label>
        <select name="team2" id="select2">
            <option>TeamName1</option>
            <option>TeamName2</option>
            ...
        </select><br/>

        <label for="select3">Team 3: </label>
        <select name="team3" id="select3">
            <option>TeamName1</option>
            <option>TeamName2</option>
            ...
        </select><br/>

        <label for="select4">Team 4: </label>
        <select name="team4" id="select4">
            <option>TeamName1</option>
            <option>TeamName2</option>
            ...
        </select><br/>

        <input type="submit" name="submit" value="Submit">

    </form>

<?php

    if (!empty($_POST['submit'])) {

        $randnumber = rand(1, 4);

        echo $_POST['team' . $randnumber];

    }

?>

</body>
</html>

I hope my answer will be useful for you

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement