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条)

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答