Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
102
rated 0 times [  108] [ 6]  / answers: 1 / hits: 56164  / 12 Years ago, mon, august 13, 2012, 12:00:00

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


More From » php

 Answers
36

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.


[#83685] Friday, August 10, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
turnerf

Total Points: 620
Total Questions: 101
Total Answers: 109

Location: French Polynesia
Member since Tue, Jul 7, 2020
4 Years ago
turnerf questions
;