jquery克隆与HTML下拉选项两个下拉选择相同的值一个警报应该选择不同的值



目前正在进行jquery克隆,用户单击添加它将克隆div完美,但我有下拉菜单。如果用户在下拉菜单中选择手机,而在其他下拉菜单中选择相同的手机,则应该重复查找,并且下拉菜单的值必须清除。

 $('.slt_major select option:selected').each(function(i, e) {
 alert("check");
    //Check if values match AND if not default AND not match changed item to self
    if ($(e).val() == cI.val() && $(e).val() != 0 && $(e).parent().index() != cI.index()) {
        alert('Duplicate found!');
        cI.val('0');
    }
}); 

我无法看到错误在哪里,甚至警报也没有生成。这是小提琴的链接。

谢谢。

这是:演示

首先我想纠正你的添加部分,因为你在cloned row的内部elements中添加了重复的id s。因此,只需更改代码如下,并检查内联注释。

$(document).on("click", ".btn_more", function () { 
        var $clone = $('.cloned-row:eq(0)').clone();
        $clone.find('[id]').each(function(){
            this.id=this.id +(count) //change the id of each element by adding count to it
        });
        $clone.find('.btn_more').after("<input type='button' class='btn_less1 phn_del' value='Del' id='buttonless"+count+"'/>")
        $clone.attr('id', "added"+(count)); //just append count here
        $clone.find('.preferred').attr('checked', false);
        $clone.find('.sslt_Field').val(0);
        $clone.find('.txt_CC').val('');
        $clone.find('.txt_Pno').val('');
        $(this).parents('.em_pho').after($clone);
        count++; //increment count at the end.
});

现在检查重复的options,你可以这样做。也检查内联注释:

//attach event handler to document since you need event delegation on dynamically created elements
//attach change event to class 'sslt_Field'
$(document).on('change','select.sslt_Field',function(event) {
    var cI = $(this); //store a reference
    var others=$('select.sslt_Field').not(cI);
    //store reference to other select elements except the selected one
    $.each(others,function(){
       //iterate through remaining selects 
       if($(cI).val()==$(this).val() && $(cI).val()!="")//check if value has been 
       //already selected on other select
       {
           $(cI).val('');//empty the value
           alert('already selected');//display alert.
       }
    });
});

最新更新