Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Text From <option> Tag Using PHP

Tags:

text

php

option

get

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?

like image 325
Abdul wahab Avatar asked Jul 20 '11 20:07

Abdul wahab


People also ask

How to get value From option tag in 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.

How do I get the text value of a selected option in PHP?

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.)

How to get values From dropdown in PHP?

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.

How do you get the selected value of dropdown in PHP without submit?

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"; ?>


1 Answers

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.

like image 142
serialworm Avatar answered Sep 30 '22 09:09

serialworm