I want to get text inside the <option>
tags as well as its value.
Example
<select name="make">
<option value="5"> Text </option>
</select>
I used $_POST['make'];
and I get the value 5
but I want to get both value and the text.
How can I do it using PHP?
To get the selected value of the <select> element, you use the $_POST superglobal variable if the form method is POST and $_GET if the form method is GET . Alternatively, you can use the filter_input() function to sanitize the selected value.
The text for the selected option is not passed through the HTML form. If you want the text, you have to store that in a hidden HTML input on your page, or you need to add some business logic in your PHP code to translate the value of ìd into the text (through a switch statement, or by querying a database, etc.)
Get Multiple Selected Values of Select Dropdown in PHPAdd the multiple tag with select tag also define array with name property. Make sure the Fruits array is not empty, run a foreach loop to iterate over every value of the select dropdown. Display the selected values else show the error message to the user.
php $selected_option=$_POST['option_value']; //Do what you need with this value, then echo what you want to be returned. echo "you have selected the option with value=$selected_option"; ?>
In order to get both the label and the value using just PHP, you need to have both arguments as part of the value.
For example:
<select name="make">
<option value="Text:5"> Text </option>
</select>
PHP Code
<?php
$parts = $_POST['make'];
$arr = explode(':', $parts);
print_r($arr);
Output:
Array(
[0] => 'Text',
[1] => 5
)
This is one way to do it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With