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 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用