动态添加下拉菜单并排除所选选项

时间:2016-02-04 10:17:55

标签: javascript jquery html css

正如我在标题中提到的,我正在尝试构建动态下拉菜单。一旦用户从列表选项中选择,就会从其他下拉列表中排除(禁用)相同的选项。

到目前为止,我已经构建了添加/删除功能。但我不知道从禁用所选选项开始解决这个问题。

Here's jsfiddle link

   $('.multi-field-wrapper').each(function() {
    var $wrapper = $('.multi-fields', this);
    $(".add-field", $(this)).click(function(e) {
        $('.multi-field:first-child', $wrapper).clone(true).appendTo($wrapper).find('input').val('').focus();
    });




    $('.multi-field .remove-field', $wrapper).click(function() {
        if ($('.multi-field', $wrapper).length > 1)
            $(this).parent('.multi-field').remove();
    });
});

var defaultTime = "<option selected disabled>Choose time</option><option>Whole day</option>";
var i, b, a, clock = "";
var min = ["00", "15", "30", "45"];

for(a = 0; a <= 1; a++){
    if(a == 0){
        for (i = 0; i <= 11; i++) {
            if(i <= 9) {
                for (b = 0; b < min.length; b++) {
                    clock += "<option>" + "0" + i + ":" + min[b] + " AM" + "</option>";
                }
            }else{
                for (b = 0; b < min.length; b++) {
                    clock += "<option>" + i + ":" + min[b] + " AM" + "</option>";
                }
            }
        }
    }else{
        for (i = 0; i <= 11; i++) {
            if(i <= 9) {
                for (b = 0; b < min.length; b++) {
                    clock += "<option>" + "0" + i + ":" + min[b] + " PM" + "</option>";
                }
            }else{
                for (b = 0; b < min.length; b++) {
                    clock += "<option>" + i + ":" + min[b] + " PM" + "</option>";
                }
            }
        }
    }
}

document.getElementById("clock").innerHTML = defaultTime + clock;

知道我应该从哪里开始?任何帮助都会有所帮助。

谢谢!

1 个答案:

答案 0 :(得分:1)

您必须将所选选项的对象设为:

        var foo = []; 
          $('.times :selected').each(function(i, selected){ 
          foo[i] = $(selected).text(); 
        });

在此之后,仅使用foo对象

中的值设置选项禁用
        $.each(foo, function(entry){
            console.log(foo[entry]);
            $(".times option:contains('"+foo[entry]+"')").attr("disabled","disabled");
        });

小提琴链接:https://jsfiddle.net/k4do7Lg2/1/