开发者

SELECTED not working with <option> tag inside a for loop/ while loop

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!!


Put your if condition out of quotes

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

}


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.


here is the problem

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

SolutionL

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜