1

Guys I have a dropdown list which, when i press the button, i want to mark the selected row automatically! my code so far is shown below, but i cant get it work... with ' " etc.

echo "<select id='form' name=form style='width:auto' class='form-control'>
<optgroup label='form_name'>";

foreach($results as $result)                                    
{
    $ID      = $result->ID;
    $name    = $result->name;
    $address = $result->address;

    echo '<option value=$ID '. 

    **if(isset($_GET['form']) &&  $_GET['form'] == $ID ){  .' selected="selected" '. } else { .''. }**                               

    .'>'.$ID. ". " .$name. " [" .$address.']</option>'; 

}                               
echo "</optgroup>
</select>;  

thanks in advance!!!

2
  • You should use " " quotation for $ID to be used "<option value=$ID " Commented Mar 25, 2016 at 10:57
  • "<select id='form' name=form style='width:auto' you have to put name in quotation marks Commented Mar 25, 2016 at 10:58

2 Answers 2

1

You have to use the ternary operator. The ternary operator is a simple "if then else" in just one line.

echo '<select id="form" name="form" style="width:auto" class="form-control">';
    echo '<optgroup label="form_name">';

    foreach ($results as $result) {
        $id      = $result->ID;
        $name    = $result->name;
        $address = $result->address;

        echo '<option value="' . $id . '" ' . (isset($_GET['form']) && $_GET['form'] == $id ? 'selected="selected"' : '') . '>' . $id . '. ' . $name . ' [' . $address . ']</option>';
    }

    echo '</optgroup>';
echo '</select>';
Sign up to request clarification or add additional context in comments.

Comments

0

You can rewrite your code in this way:

echo "<select id='form' name=form style='width:auto' class='form-control'>
    <optgroup label='form_name'>";
    foreach($results as $result)                                    
    {
        $ID      = $result->ID;
        $name    = $result->name;
        $address = $result->address;

        $selected = ( isset($_GET['form']) &&  $_GET['form'] == $ID ) ? ' selected="selected" ' : '';

        echo '<option value=$ID '
                . $selected
                .'>'.$ID. ". " .$name. " [" .$address.']</option>'; 
    }                               
echo " </optgroup>
           </select>;

3 Comments

they were both the same answer i presume!!
@ΗλιαςΤσορομωκος correct, we answered simultaneously, so I sow the other user's answer after posting mine, otherwise I will not answer ;)
i'll give the bonus to this answer because it's more tidy from the other but plz no hard feelings ok?! thank you both of you!!!

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.