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

时间:2014-07-01 21:23:43

标签: javascript php jquery forms

我有一个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>";

2 个答案:

答案 0 :(得分:1)

似乎是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>"

答案 1 :(得分:0)

根据$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>";
?>