控制选择表单上的选项数量

control number of options on select form

本文关键字:选项 选择 表单 控制      更新时间:2023-09-26

我有一个int类型的php变量$a。现在如果$a=1;,那么前两个选项应该只可见,如果$a=2;,那么前三个选项应该只出现,以此类推。我怎样才能做到这一点呢?

echo "<form class='form-horizontal'>
        <fieldset  >   
            <span class='control-group' >
            <span  class='controls'>
                <select id='fl' class='form-control' style='cursor:pointer;'>
                    <option " . ($default == 0 ? "selected='selected'" : "") . " style='display:none;' value='0'>Select</option>
                    <option " . ($default == 1 ? "selected='selected'" : "") . " value='1'>Option1</option>
                    <option " . ($default == 2 ? "selected='selected'" : "") . " value='2'>Option2</option>
                </select>
            </span>
        </span>
        <div><button id='mybtn' type='button'>Save</button></div>
        </fieldset>
    </form>";

似乎是for循环的绝佳机会。

// put your values into an array for easy access inside the loop
$options = array(
    1 => "Option1",
    2 => "Option2",
    3 => "Option3",
    etc...
);
// output the beginning of the <select> html
echo "<select id='fl' class='form-control' style='cursor:pointer;'>
         <option " . ($default == 0 ? "selected='selected'" : "") . " style='display:none;' value='0'>Select</option>";
// loop through items until we reach our limit, set in $a
for ($i = 1; $i < $a; $i++) {
    echo "<option " . ($default == $i ? "selected='selected' " : "") . "value='" . $i . "'>" . $options[i] . "</option>";
}
// output the end of the <select> html to close it off
echo "</select>"

根据$a的值在echo之前放置选项,并在echo中使用该变量

<?php
$options = '';
if($a==1)
{
    $options = "<option " . ($default == 0 ? "selected='selected'" : "") . " style='display:none;' value='0'>Select</option>
                <option " . ($default == 1 ? "selected='selected'" : "") . " value='1'>Option1</option>";
}
else if($a==2)
{
    $options = "<option " . ($default == 0 ? "selected='selected'" : "") . " style='display:none;' value='0'>Select</option>
                <option " . ($default == 1 ? "selected='selected'" : "") . " value='1'>Option1</option>
                <option " . ($default == 2 ? "selected='selected'" : "") . " value='2'>Option2</option>";
}
echo "<form class='form-horizontal'>
        <fieldset  >   
            <span class='control-group' >
            <span  class='controls'>
                <select id='fl' class='form-control' style='cursor:pointer;'>
                    ".$options."
                </select>
            </span>
        </span>
        <div><button id='mybtn' type='button'>Save</button></div>
        </fieldset>
    </form>";
?>