Abilash Amarasekaran
Abilash Amarasekaran

Reputation: 838

change the selected option in html select based on variable value

My code is like

    echo("<td>$row[Status]</td>");
    echo("<td>
    <select name=\"choose\" id=\"Choose\" onChange=\"\">
    <option value=\"Unverified\">Unverified</option>
    <option value=\"Approved\">Approve</option>
    <option value=\"Decline\">Decline</option>
    <option value=\"Pending\">Pending</option>                   
    </select>
    </td>");

Here is what I want to do if ($row[Status] == Approved) then the code should change like this

.
.
<option value=\"Approved\" Selected>Approve</option>
.
.

The simplest way would be to create a simple if condition for all but there must be smarter way to do it. Any ideas?

I would prefer to keep it in php itself. And if you are going use a bit more complicated symbols like a => b Please explain why it is being used and what it does.

Upvotes: 0

Views: 4430

Answers (3)

Abilash Amarasekaran
Abilash Amarasekaran

Reputation: 838

    echo("<td>$row[Status]</td>");
    $search= "$row[Status]\"";
    $replace= "$row[status]\" Selected";
    $subject="<td>
    <select name=\"choose\" id=\"Reason\" onChange=\"\">
         <option value=\"Unverified\">Unverified</option>
         <option value=\"Approved\">Approve</option>
         <option value=\"Decline\">Decline</option>
         <option value=\"Pending\">Pending</option>                     
         </select>
         </td>";
$subject=str_replace($search, $replace, $subject);
echo $subject;

I used the above and got my desired result... wasted an hour not knowing that str_replace would return the edited value and not replace $subject. Thanks everyone.

Upvotes: 0

Tom
Tom

Reputation: 199

Try this! It'll loop through the whole array, and select the selected option when reached. Is this what you were looking for?

(Hasn't been tested)

echo ("<select name=\"choose\" id=\"Choose\" onChange=\"\">");

$sel["Unverified"] = "Unverified";
$sel["Approved"] = "Approve";
$sel["Decline"] = "Decline";
$sel["Pending"] = "Pending";

$selected = "Approved";

foreach($sel as $key => $value) {
    if ($selected == $key) {
        echo ("<option value=\"$key\">$value</option>");
    }
    else {
        echo ("<option value=\"$key\" selected>$value</option>");
    }
}

echo ("</select>");

?>

Upvotes: 0

Nicolas78
Nicolas78

Reputation: 5144

create an array of the possible values, and then create the options in the loop. that way, you only have to write one if condition that matches the current to the desired (here, approved) value

Upvotes: 1

Related Questions