Skip to content Skip to sidebar Skip to footer

Php Code To Get Selected Text Of A Combo Box

I have a combo box named 'Make'. In that combo box I'm loading vehicle manufacturer names. When I click SEARCH button I want to display the selected manufacturer name. Below is par

Solution 1:

Try with this. You will get the select box value in $_POST['Make'] and name will get in $_POST['selected_text']

<formmethod="POST" ><labelfor="Manufacturer"> Manufacturer : </label><selectid="cmbMake"name="Make"onchange="document.getElementById('selected_text').value=this.options[this.selectedIndex].text"><optionvalue="0">Select Manufacturer</option><optionvalue="1">--Any--</option><optionvalue="2">Toyota</option><optionvalue="3">Nissan</option></select><inputtype="hidden"name="selected_text"id="selected_text"value="" /><inputtype="submit"name="search"value="Search"/></form><?phpif(isset($_POST['search']))
{

    $makerValue = $_POST['Make']; // make value$maker = mysql_real_escape_string($_POST['selected_text']); // get the selected textecho$maker;
}
 ?>

Solution 2:

Put whatever you want to send to PHP in the value attribute.

<selectid="cmbMake"name="Make" ><optionvalue="">Select Manufacturer</option><optionvalue="--Any--">--Any--</option><optionvalue="Toyota">Toyota</option><optionvalue="Nissan">Nissan</option></select>

You can also omit the value attribute. It defaults to using the text.

If you don't want to change the HTML, you can put an array in your PHP to translate the values:

$makes = array(2 => 'Toyota',
               3 => 'Nissan');

$maker = $makes[$_POST['Make']];

Solution 3:

You can achive this with creating new array:

<?php$array = array(1 => "Toyota", 2 => "Nissan", 3 => "BMW");

if (isset ($_POST['search'])) {
  $maker = mysql_real_escape_string($_POST['Make']);
  echo$array[$maker];
}
?>

Solution 4:

if you fetching it from database then

<selectid="cmbMake"name="Make" ><optionvalue="">Select Manufacturer</option><?php$s2="select * from <tablename>"; 
$q2=mysql_query($s2); 
while($rw2=mysql_fetch_array($q2)) { 
?><optionvalue="<?phpecho$rw2['id']; ?>"><?phpecho$rw2['carname']; ?></option><?php } ?></select>

Solution 5:

Change your select box options value:

<selectid="cmbMake"name="Make" ><optionvalue="">Select Manufacturer</option><optionvalue="Any">--Any--</option><optionvalue="Toyota">Toyota</option><optionvalue="Nissan">Nissan</option></select>

You cann't get the text of selected option in php. it will give only the value of selected option.

EDITED:

<selectid="cmbMake"name="Make" ><optionvalue="0">Select Manufacturer</option><optionvalue="1_Any">--Any--</option><optionvalue="2_Toyota">Toyota</option><optionvalue="3_Nissan">Nissan</option></select>

ON php file:

$maker = mysql_real_escape_string($_POST['Make']);
$maker = explode("_",$maker);
echo$maker[1]; //give the Toyota
echo$maker[0]; //give the key 2

Post a Comment for "Php Code To Get Selected Text Of A Combo Box"