1

i want one of the options in drop down to be selected by default, Please see the code

<?php
class html{

    function output(){

        $html='<td>'.'<select id="out">';
        for($i=0;$i<21;$i++){
            $html.='<option value="$i" if($i==5) { selected } >'. $i .'</option>';
        }

        return $html;
    }
}

echo html::output();
?>

Here i want value 5 to be selected by default,But I am getting selected value as 20. THANK YOU!!

2
  • Programming does not work that way. Commented Jul 1, 2011 at 5:35
  • I did not follow you , Sorry Could you make it clear. What is problem here Commented Jul 1, 2011 at 5:37

3 Answers 3

2

Put your if condition out of quotes

for($i=0;$i<21;$i++)
{
   $selected=($i==5) ? 'selected' : '';
   $html.="<option value='$i'  $selected>". $i ."</option>";

}
Sign up to request clarification or add additional context in comments.

4 Comments

Will fail due to improper quoting. May also be wrong depending on desired HTML version/adherence.
@ignacio: Where is the improper quotes?
You had the second line in single quotes before.
@ignacio: Oh, That was there with initial answer but improved immediately
1

You're line is incorrect. Use this instead:

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

I'm making use of the ternary comparison operator.

Comments

1

here is the problem

$html.='<option value="$i" if($i==5) { selected } >'. $i .'</option>';

SolutionL

$html.="<option value=\"$i\" ".($i==5? "selected": ""). "$i </option>";

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.