jQuery动态为第二个选择框填充optgroup [英] Jquery populate optgroup for second selectbox dynamically

查看:135
本文介绍了jQuery动态为第二个选择框填充optgroup的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在两个多重选择框中有很长的选项列表,我想基于select_A动态填充select_B的选项,例如:

I have a very long list of options in two multiple select box, I want to populate dynamically the options for select_B based on select_A, for instance:

如果我从select_A分别选择opt1和opt2,则select_B将仅显示带有id=sub1id=sub2的optgroup选项,如果我取消选择opt1并从select_A选择opt3,则select_B删除optgroup sub1并保留sub2sub3,依此类推,并具有控制灵活性.

I multiple select opt1 and opt2 from select_A, select_B will show the options which is optgroup with id=sub1 and id=sub2 only, if I deselect opt1 and select opt3 from select_A, select_B will remove optgroup sub1 and remain sub2 and sub3, and so on with flexibility of control.

<select id="select_A" multiple="multiple" size="10">
    <optgroup label="group 1">
        <option value="opt1" id="main1">opt1</option>
        <option value="opt2" id="main2">opt2</option>
    <optgroup label="group 2">
        <option value="opt3" id="main3">opt3</option>
</select>

<select id="select_B" multiple="multiple" size="10">
    <optgroup label="opt1" id="sub1" style="display:none;">
        <option value="1A">1A</option>
        <option value="1B">1B</option>

    <optgroup label="opt2" id="sub2" style="display:none;">
        <option value="2A">2A</option>
        <option value="2B">2B</option>

    <optgroup label="opt3" id="sub3" style="display:none;">
        <option value="3A">3A</option>
        <option value="3B">3B</option>
</select>

我已经有一个解决方案,可以在

I already have a solution for hiding optgroup in Chrome and IE from here:

<script>
$(document).ready(function() {
    $.fn.hideOptionGroup = function() {
        $(this).hide();
        $(this).children().each(function(){
        $(this).attr("disabled", "disabled").removeAttr("selected");
    });

    $(this).appendTo($(this).parent());

    }

    $.fn.showOptionGroup = function() {
        $(this).show();    
        $(this).children().each(function(){
        $(this).removeAttr("disabled");
    });

        $(this).prependTo($(this).parent());
        $(this).parent().animate({scrollTop:0},0);
    }



    $("#sub1,#sub2").showOptionGroup();
    $("#sub1,#sub2").hideOptionGroup();
});
</script>

请帮忙,谢谢.

推荐答案

请参见:示例

 $("#select_A").change(function () {
    $("#select_B").children("optgroup").children().prop("disabled", "disabled").prop("selected", false);
    var arr = $(this).val();
    for (var i = 0; i < arr.length; i++) {
        $("#select_B").children("optgroup[label=" + arr[i] + "]").children().prop("disabled",false).prop("selected", "selected");
    }
    $("#select_B").focus();
 });

这篇关于jQuery动态为第二个选择框填充optgroup的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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