Reputation: 23
I am trying to display the month and corresponding birthstone using php. I used an associative array to dynamically populate options for a select and I've gotten so far as to print the birthstone, but I can't seem to figure out how to access the option names to display the month as well. This is for an assignment I've already handed in (of which, what I have satisfies the requirements. I'm looking to figure out the non-required part.
Can anyone point me in the right direction on accessing the values for option name=""
Thanks!
<html>
<body>
<div>
<h1>Birthstones by Month</h1>
<p>Select a Month from the dropdown to reveal your birthstone</p>
<form action="birthstone.php" method="post">
<?php
$months = array ( 'January' => 'Garnet', 'February' => 'Amethyst', 'March' => 'Aquamarine', 'April' => 'Diamond', 'May' => 'Emerald',
'June' => 'Pearl', 'July' => 'Ruby', 'August' => 'Peridot', 'September' => 'Sapphire', 'October' => 'Tourmaline', 'November' => 'Citrine',
'December' => 'Tanzanite');
print "<select name='bstones'>";
foreach($months as $month => $stone) {
print "print <option value='".$stone ."'name='".$month ."'>" . $month . "</option>";;
}
print "</select> <br />";
?>
<button type="submit" name="sumbit" value="submit">Reveal my Birthstone</button>
</form>
<?php
if (isset($_POST['bstones']))//this is validating the selection
{
$bstones = $_POST['bstones']; //this is assigning a variable name to the option values from the select
print "Your birthstone is <b>$bstones</b>";
}
//I really wanted to display the month selected as well as the stone, but I could not figure out how to get the month to print out. When I try to google this issue,
//I only see instructions on how to access the option value, not the name.
?>
</div>
</body>
</html>
Upvotes: 0
Views: 43
Reputation: 401
The select
has a name
property, but option
tags don't. So you can't get the name of the option.
What you should do is set value of the option to the month name, and then on birthstone.php
, use the $months
array to get the birthstone name associated to that month.
So:
foreach($months as $month => $stone) {
print "<option value='".$month ."'>" . $month . "</option>";
}
And then:
<?php
if (isset($_POST['bstones']))//this is validating the selection
{
$month = $_POST['bstones']; //this is assigning a variable name to the option values from the select
print "You selected $month, so your birthstone is <b>". $months[$month] ."</b>";
}
Upvotes: 0
Reputation: 780871
Use the array keys as the option values, not the array values.
print "<select name='months'>";
foreach($months as $month => $stone) {
print "print <option value='".$month ."'name='".$month ."'>" . $month . "</option>";;
}
print "</select>";
Then you can use this to look up the stone in the array.
if (isset($_POST['months']))//this is validating the selection
{
$month = $_POST['months'];
print "Your birth month is <b>$month</b>, your birthstone is <b>{$months[$month]}</b>";
}
Upvotes: 0