hoppy_amz007
hoppy_amz007

Reputation: 9

how can I use an if statement within a php variable?

I am using ajax to call a file on click of a 'card' to display a dialog box. It worked fine as normal html with php but now that I've saved it as a php variable it doesn't like the if statement and the drop downs always show the default 'choose' option. Can this be done? Or maybe I'm just writing it wrong?

$html.="<select name='priority'>";
$html.="<option>---Choose---</option>";
$html.="<option if ($priority == 'Low') echo 'selected' value='Low'>Low</option>";
$html.="<option if ($priority == 'Normal') echo 'selected' value='Normal'>Normal</option>";
$html.="<option if ($priority == 'High') echo 'selected' value='High'>High</option>";
$html.="<option if ($priority == 'Critical') echo 'selected' value='Critical'>Critical</option>";
$html.="</select>";

Upvotes: 0

Views: 91

Answers (2)

Meisam Mulla
Meisam Mulla

Reputation: 1871

It should be done like this:

$html .= "<option " .
         (($priority == 'Low') ? 'selected' : '') .
         " value='Low'>Low</option>";

Not using the Ternary operator:

$html .= "<option ";

if ($priority == 'Low') {
    $html .= 'selected';
}

$html .= " value='Low'>Low</option>";

Upvotes: 5

Steward Godwin Jornsen
Steward Godwin Jornsen

Reputation: 1179

You probably forget the difference. Everything you have in double quotes is a string. Try it with ternary:

        $priority = "Normal";
        $html = "";

        //Use from here
        $html .= "<select name='priority'>";
        $html.="<option>---Choose---</option>";
        $html.="<option ";
        $html.= (($priority == 'Low') ? 'selected' : '');
        $html.=" value='Low'>Low</option>";
        $html.="<option ";
        $html.=(($priority == 'Normal') ? 'selected' : '');
        $html.=" value='Normal'>Normal</option>";
        $html.="<option ";
        $html.=(($priority == 'High') ? 'selected' : '');
        $html.=" value='High'>High</option>";
        $html.="<option ";
        $html.=(($priority == 'Critical') ? 'selected' : '');
        $html.=" value='Critical'>Critical</option>";
        $html.="</select>";
        echo $html;
        exit;

Tested!

Upvotes: 1

Related Questions