0

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>";

2 Answers 2

5

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>";
Sign up to request clarification or add additional context in comments.

4 Comments

Indeed, just concatenate the result instead of embedding it within a string.
For reference, he's using the Ternary operator: php.net/manual/en/language.operators.comparison.php
You might want to write that without the ternary as well – it's clear the person asking isn't well versed in this sort of thing.
Thank you, no not well versed at all, only starting dabbling
1

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.