doujiang2641 2009-12-07 11:01
浏览 31
已采纳

如何在第一个下拉列表中使用所选值填充第二个下拉列表?

Say I have two drop downs which are populated when the my jsp loads

 <select id="Group" name="group"> -- first drop down
    <option value="0001">1</option>
    <option value="0002">2</option>
 </select>

 <select id="subGroup" name="class"> -- second drop down
    <option value="0001-000">A</option> -- sub group associated with option value 001
    <option value="0001-010">B</option>
    <option value="0001-020">C</option>
    <option value="0001-030">D</option>
    <option value="0001-040">E/option>
    <option value="0002-000">F</option> -- sub group associated with option value 002
    <option value="0002-010">G</option>
    <option value="0002-020">H</option>
    <option value="0002-040">I</option>
  </select>

Now I need to filter the second drop down based on the selected value in first drop down. I can't use the PHP code which uses the DB callback methods. in my script I have something like this.

   $("#Group").change(function() {
     var groupVal = $(this).find("option:selected").val();
     $('#subGroup option').filter(function( {return!$(this).val().indexOf(groupVal)!=-1);}).remove();
    });

the script is working fine, it removes all the options other then the one selected. but my problem is that next time when i select other value in first drop down, second drop down goes empty. I even worked with hide/show but guess they wont work with <select> :(

is there any way by which I can repopulate the second drop down when I selected some other option in first drop down?

  • 写回答

4条回答 默认 最新

  • dshnx48866 2009-12-07 11:12
    关注

    If you are removing elements, you aren't getting them back. Use hide() and show() as you yourself suggested:

    $("#Group").change(function() {
        var groupVal = $(this).find("option:selected").val();
        $('#subGroup option').hide();
        $('#subGroup option[value^='+groupVal+']').show();
    });
    

    In other words, every time the #Group selectbox is changed, hide all options in #subGroup and show only the ones whose value attribute starts with groupVal.

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部