Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the text of the selected option using php [duplicate]

in the following:

<form  action="test.php"  method="POST">  
    <select id="test" name="test">
     <option value="1">Test One</option>
     <option value="2">Test Two</option>
    </select>
</form>

in test.php, I can get 1 or 2 as follow:

$result=$_POST['test'];

How can I get the text of the selected option (i.e. "Test One" or "Test Two") using php

like image 322
Max_Salah Avatar asked Aug 13 '12 00:08

Max_Salah


4 Answers

This is not something that can be done through PHP alone. The PHP script can only "see" the information which is posted (the value for the selected option that is posted). You can use javascript to alter a hidden input field with the text contents of a selected option, and this will be included in the $_POST array:

<form  action="test.php"  method="POST">  
    <select id="test" onchange="document.getElementById('text_content').value=this.options[this.selectedIndex].text">
     <option value="1">Test One</option>
     <option value="2">Test Two</option>
    </select>

<input type="hidden" name="test_text" id="text_content" value="" />
</form>

This will make the $_POST['test_text'] available with the selected index (but you should also force the onchange() function when the page loads so that it will be populated even if the user leaves the select field at the default value.

like image 61
Ben D Avatar answered Nov 15 '22 03:11

Ben D


Only the value of the form control will be sent to the server. An easy way to send both is to simply include both in the the value:

<select name="test">
    <option value="1|Test one">Test one</option>
    <option value="2|Test two">Test two</option>
</select>

And then:

$test = explode('|', $_POST['test']);

Then you'll end up with $test[0] being "1" and $test[1] being "Test one".

like image 36
powerbuoy Avatar answered Nov 15 '22 03:11

powerbuoy


You can't; that information is not sent back to the server. You will need to look at how you generated the HTML in the first place and get the text from there.

like image 39
Ignacio Vazquez-Abrams Avatar answered Nov 15 '22 03:11

Ignacio Vazquez-Abrams


It is not sent so the only way to get it is having an array mapping values to titles in your PHP code.

like image 35
ThiefMaster Avatar answered Nov 15 '22 04:11

ThiefMaster