jQuery/js separating 2 drop down values

孤街醉人 提交于 2019-12-25 04:26:59

问题


I'm using Eric Hynds jQuery MultiSelect Widget. I'm actually using 2 separate widgets that when checked, creates a dynamic checkbox w/ value attached to a corresponding 'Main' checkbox if 'Main' checkbox is checked. Please see my fiddle with comments inside to illustrate my problem:http://jsfiddle.net/3u7Xj/52/

How to separate the 2 widgets to show in corresponding sections and still only allow the user to choose 2 combined from either?

$(document).ready(function() {
    $(".multiselect").multiselect({
        header: "Choose up to 5 areas total",
        click: function (event, ui) {

            if (ui.checked && $(".multiselect").children(":checked").length >= 2) {
                return false;
            }

            var lbl = ui.value;
            if(ui.checked){
                var ctrl = '<input type="checkbox" name="chk" checked="checked" class="chk" id="'+lbl+'">';
                $("[id^=Main]:checked").each(function(){
                    $(this).nextAll('.holder:first').append('<div>'+ctrl+lbl+'</div>');    
                });
            }
            else {
                $("[id^=Main]:checked").each(function(){
                    $(this).nextAll('.holder:first').find('div input[id="'+lbl+'"]').parent().remove();
                });
            }

        },
        selectedList:5
    });
});

回答1:


So I modified the condition and it works as it should, I hope that it will suit you.

var number1=$("#dropdown1").children(":checked").length,
    number2=$("#dropdown2").children(":checked").length;

if (ui.checked && ((number1 + number2 >=4) || $(this).children(":checked").length >= 2)){
    return false;
}

Demo here

If you want to only two from both selects and modify the condition as follows:

var number1=$("#dropdown1").children(":checked").length,
    number2=$("#dropdown2").children(":checked").length;

if (ui.checked && ((number1 + number2 >=2) || $(this).children(":checked").length >= 2)){
    return false;
}

Demo here

Adapted to the requirements in the comment

individual segments inserted into the div. Adjusted control function click

to:

$(this).parent("div").find("[id^=Main]:checked").each(function(){
      $(this).nextAll('.holder:first').append('<div>'+ctrl+lbl+'</div>');    
});

Demo here



来源:https://stackoverflow.com/questions/21335744/jquery-js-separating-2-drop-down-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!