I am attempting to echo
the name of a selected dropdown rather than its value. I understand that echo
ing a dropdown's value can be achieved by implementing something such as:
$variable = $_POST['vehicleStyle'];
echo $variable;
where vehicleStyle
is the <select>
name.
However, I am not after the value
I after the option's name.
Here is my PHP. I am extracting data from a XML Document where $k
equals the option name and $v
equals its value.
<html>
<body>
<?php
$xml = file_get_contents('note.xml');
$dom = new DOMDocument();
$dom->loadXML($xml);
?>
<form action="additionalinfo.php" method=POST>
<select name="vehicleStyle">
<option selected="selected">Choose style</option>
<?php
foreach ( $dom->getElementsByTagName('style') as $styletwo ) {
$styleid = $styletwo->getAttribute("name");
$styleData [$styleid]= $styletwo->getAttribute("id");;
}
foreach ($styleData as $k=>$v){
?>
<option value='<?php echo $v;?>'><?php echo $k;?> </option>
<?php
}
?>
</select>
<br>
<button class="button">Submit</button>
</form>
</body>
</html>
This outputs a dropdown containing two values: 'Audi=>292015` and 'BMW=>292016'. If I add
$variable = $_POST['vehicleStyle'];
echo $variable;
to my code, I get either 292015
or 292016
(whichever is selected). How can I echo the dropdown name, either Audi
or BMW
?
Thanks!
How about...
<option value='<?php echo $v . '|' . $k;?>'><?php echo $k;?> </option>
Then
$variable = $_POST['vehicleStyle'];
$variable = explode('|', $variable);
echo $variable[0]; //The "value"
echo $variable[1]; //The "text"
Might make some validation more difficult but it should get you what you need.