带有HTML下拉选项的jquery clone选项下拉选择相同的值,警报应选择不同的值

时间:2015-10-08 06:17:21

标签: javascript jquery html

目前正在使用jquery clone,用户点击添加它将完美克隆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');
    }
}); 

即使警报未生成,我也无法看到错误的位置。这是fiddle link

感谢。

1 个答案:

答案 0 :(得分:2)

所以这里是: DEMO

首先,我想更正您的添加部分,因为您将重复的id添加到elements的内部cloned row中。因此,只需更改下面的代码并检查内联注释。

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