aynaz
aynaz

Reputation: 89

Get text of select box in php page

I have select box in PHP and want text selected item of that:

<form action="" method="get" target="" dir="rtl" class="w3-container">
  <?php  
 echo " <select id='p1' name='p1'  >";
 echo "<option  value='*'>Choose person</option>";
sql code

 $result2 = mysql_query($query2,$con);
 while($row2 = mysql_fetch_array($result2))
 {
$row2['name'];
echo "<option  value='".$row2['id']."'>".$row2['name']."</option>"; 
}
echo " </select>";
 mysql_close($con);
 ?>

<input  class="w3-btn w3-hover-yellow" name="" type="submit" value="جستجو">
</form>

<?php
if(isset($_GET['p1']) and $_GET['p1'] != "*")
{


    if ($name_insert=trim($_GET["p1"]))
{    
        if ($strWhere == ""){
        $strWhere .= "name_insert='".trim($name_insert)."' ";
        $getPage .= "&name_insert=".($name_insert);}
        else{
        $strWhere .= " and name_insert='".trim($name_insert)."' ";
        $getPage .= "&name_insert=".($name_insert);}
    }
}
?>

I want code that get text of select box in $name_insert. This code gets value of that.

Upvotes: 0

Views: 57

Answers (1)

shubham715
shubham715

Reputation: 3302

You can use javascript and save selected option text in a hidden field.

Example

<form  action=""  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>

PHP

$getOptionText = $_POST['test_text'];

Replace your code with this code

<form action="" method="get" target="" dir="rtl" class="w3-container">

 <select id='p1' name='p1'  onchange="document.getElementById('text_content').value=this.options[this.selectedIndex].text">
 <option  value='*'>Choose person</option>
<?php
 $result2 = mysql_query($query2,$con);
 while($row2 = mysql_fetch_array($result2))
 { 
echo "<option  value='".$row2['id']."'>".$row2['name']."</option>"; 
}
mysql_close($con);
 ?>
</select>
 <input type="hidden" name="test_text" id="text_content" value="" />

<input  class="w3-btn w3-hover-yellow" name="" type="submit" value="جستجو">
</form>

<?php
if(isset($_GET['p1']) and $_GET['p1'] != "*")
{
   $getValueOfText =  $_GET['test_text'];
   echo $getValueOfText;

    if ($name_insert=trim($_GET["p1"]))
{    
        if ($strWhere == ""){
        $strWhere .= "name_insert='".trim($name_insert)."' ";
        $getPage .= "&name_insert=".($name_insert);}
        else{
        $strWhere .= " and name_insert='".trim($name_insert)."' ";
        $getPage .= "&name_insert=".($name_insert);}
    }
}

?>

Upvotes: 1

Related Questions