Egrodo
Egrodo

Reputation: 349

How can I echo out the users dropdown selection?

I'm trying to echo to the screen what a user selects from a dropdown menu. So whenever the user selects a number, it updates the text below it in to display what they selected. Here's my code below:

<html>
<head>
</head>
<body>
<label for="numbers"></label>
<form action="drop.php">
    <select name="numbers">
    <option value="0">select number</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    </select>
    <br><br>
    <input type="submit">
</form>

<?php

if(isset($_POST['numbers']))
{
    $numbers = $_POST['numbers'];
    $error = "?";
    echo "<p>" . $numbers . "</p>";
}
?>
</body>
</html>

UPDATED MAIN CODE

Upvotes: 1

Views: 951

Answers (3)

Peter
Peter

Reputation: 630

Add method="post" to the form

<form action="drop.php" method="post">

Upvotes: 1

Sanjiv Dhakal
Sanjiv Dhakal

Reputation: 316

Try method="post" on form declaration. or use $_GET instead of $_POST ON drop.php

if(isset($_POST['numbers']))

Upvotes: 2

anFfWuy7qbJWaPp6DSOR
anFfWuy7qbJWaPp6DSOR

Reputation: 305

I suggest reading PHP's Dealing with Forms tutorial and also researching the change event.

For your code example, I've added a form element along with an "onchange" attribute to the select element which will automatically submit the form when a number is chosen.

<html>
<head>
</head>
<body>
<form action="<?php echo basename(__FILE__); ?>" method="post">
<label for="numbers">Numbers:</label>
<select name="numbers" onchange="document.forms[0].submit();">
    <option value="0">select number</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>
<input type="submit">
</form>

<?php

if (array_key_exists('numbers', $_POST)) {
    $numbers = $_POST['numbers'];
    echo '<p>' . $numbers . '</p>';
}
?>

</body>
</html>

Upvotes: 1

Related Questions