如何使用第一个下拉菜单中的选定值填充第二个下拉菜单? [英] how to populate the second drop down using the selected value in first drop down?

查看:220
本文介绍了如何使用第一个下拉菜单中的选定值填充第二个下拉菜单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有两个下拉菜单,当我的jsp加载时会填充

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>

现在,我需要根据第一个下拉列表中的选定值过滤第二个下拉列表.我不能使用使用DB回调方法的PHP代码.在我的脚本中,我有类似的内容.

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();
    });

该脚本运行正常,它删除了除所选选项之外的所有选项.但是我的问题是,下次当我在第一个下拉列表中选择其他值时,第二个下拉列表将变为空.我什至使用过隐藏/显示功能,但猜想它们不能用于<select> :(

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?

推荐答案

如果要删除元素,则不会找回它们.按照您自己的建议使用hide()show():

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();
});

换句话说,每次更改#Group选择框时,隐藏#subGroup中的所有选项,并仅显示其value属性以groupVal开头的选项.

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.

这篇关于如何使用第一个下拉菜单中的选定值填充第二个下拉菜单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆