dongpiao8821 2013-05-22 04:31
浏览 40
已采纳

在表单提交验证后重新填充下拉菜单选项

I'm working on a sign up/registration form in php that resubmits/retains the users input if everything doesn't validate properly. I've got text box, password input, and radio buttons all working but these drop down menus have been more trouble. The php code I used works for the text boxes but not these select/options, is there a better way to do this? I've cut out the majority of the options just to save space, but each goes from 0-11 months, 1-31 days, and 1900-2013 years respectively.

<select id="month" name="month" value="<?php
    if(isset($_POST['month']))
        echo htmlspecialchars($_POST['month'])?>">

    <option value="default">Month</option>
    <option value="0">January</option>
    ...
    <option value="11">December</option>

</select>
<select id="formDay" name="day" value="<?php
    if(isset($_POST['day']))
        echo htmlspecialchars($_POST['day'])?>">

    <option value="default">Day</option>
    <option value="1">1</option>
    ...
    <option value="31">31</option>

</select>
<select id="formYear" name="year" value="<?php
    if(isset($_POST['year']))
        echo htmlspecialchars($_POST['year'])?>">

    <option value="default">Year</option>
    <option value="2013">2013</option>
    ...
    <option value="1900">1900</option>

 </select>                    
  • 写回答

3条回答 默认 最新

  • duan0714 2013-05-22 05:43
    关注

    You may try this, generate values dynamically

    Day:

    echo "<select name='day'>";
    for( $i = 1; $i <= 31; $i++ )
    {
        $selectedDay = isset($_POST['day']) && $_POST['day'] == $i ? 'selected="selected"' : ''; 
        echo "<option $selectedDay value=$i>$i</option>";
    }
    echo "</select>";
    

    Month:

    $months = array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
    echo "<select name='month'>";
    for( $i = 0; $i <= 11; $i++ )
    {
        $m = $months[$i];
        $selectedMonth = isset($_POST['month']) && $_POST['month'] == $i ? 'selected="selected"' : ''; 
        echo "<option $selectedMonth value=$i>$m</option>";
    }
    echo "</select>";
    

    Year:

    echo "<select name='year'>";
    for( $i = 2013; $i >= 1900; $i-- )
    {
        $selectedYear = isset($_POST['year']) && $_POST['year'] == $y ? 'selected="selected"' : ''; 
        echo "<option $selectedYear value=$i>$i</option>";
    }
    echo "</select>";
    

    Demo Normal and Demo Selected

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?