Satain
Satain

Reputation: 9

Select default value from GET value

My website is using form editing to click on a record, which then opens up a form and allows for all of the values to be edited, and saved to append the new values. However the issue I am facing is the select, which should be using the default value from $_GET, but instead the default is coming up as the value which is first in alphabetical order, not what it should actually be. So the issue is if i edit and save, the form is automatically placing the wrong value within the select box.

The code I am using for my select is as follows:

echo "<select name='ClientCode'>";
    while ($row = mysql_fetch_array($result)) {
    echo "<option  value='" . $row['ClientCode'] ."'>" . $row['ClientName'] ."</option>";}
    echo "</select><br>";   //CLOSE DROP DOWN BOX

How can I edit the above snippet to allow my $cli = $_GET["ClientCode"] to be shown within the select box as the default value on page load

Upvotes: 0

Views: 361

Answers (4)

Beamlaku Amare
Beamlaku Amare

Reputation: 11

Use this

if($row['ClientCode'] == $_GET["ClientCode"])
{
?>
    <option selected="selected">
    Value goes here...
    </option>
<?php
}

Upvotes: 0

Rajdeep Paul
Rajdeep Paul

Reputation: 16963

Change your <select ...> ... <select> dropdown list code in the following way,

echo "<select name='ClientCode'>";
while ($row = mysql_fetch_array($result)) {
    $output = "<option  value='" . $row['ClientCode'] ."'";
    if(isset($_GET["ClientCode"]) && $row['ClientCode'] == $_GET["ClientCode"]){
        $output .= " selected='selected'";
    }
    $output .= ">" . $row['ClientName'] ."</option>";
    echo $output;
}
echo "</select><br>";

Upvotes: 3

B. Desai
B. Desai

Reputation: 16436

change your while loop like :

$cli = isset($_GET["ClientCode"])?$_GET["ClientCode"]:"";
while ($row = mysql_fetch_array($result)) {
    $selected =  ($cli == $row['ClientCode']) ? "selected" : "";
    echo "<option  value='" . $row['ClientCode'] ."' $selected >" . $row['ClientName'] ."</option>";}

Upvotes: 4

Dimash
Dimash

Reputation: 591

You need check $_GET in your loop and do selected="selected" for needed option

echo "<select name='ClientCode'>";
    while ($row = mysql_fetch_array($result)) {
    if (!empty($_GET["ClientCode") && $_GET["CleintCode"] == $row["ClientCode"]))
    {
     echo "<option  selected='selected' value='" . $row['ClientCode'] ."'>" . $row['ClientName'] ."
    </option>";
    }
    else
    {
       echo "<option  value='" . $row['ClientCode'] ."'>" . $row['ClientName'] ."
</option>";
     }
}
echo "</select><br>"

Upvotes: 0

Related Questions