Learner
Learner

Reputation: 621

jquery: No duplicate select of the same value of many drop down menus

I create a form that contains a button to add a new drop down menu (select) "I want to validate that there is no duplicate value selected" before submitting the form, Now I did via below code

jQuery method:

$('select').on('change', function(){
$("select").not(this).find("option[value="+ $(this).val() + "]").prop('disabled', true);

});

But now I have two problems:

1- If i delete one of the selects its value still disabled in all the others

2- Starting fresh with the original menu then adding for example 5 new menus the code works fine I mean without duplicated values in all the 6 menus But if I add a new one (the 7th menu) I can select any value even if its selected by the first 6 menus

Any Help ?

UPDATE:

Here is the link to JSFiddle:

https://jsfiddle.net/Somayah/oetx6f6c/

Upvotes: 1

Views: 1665

Answers (1)

wrxsti
wrxsti

Reputation: 3504

I was able to get something working like this: DEMO

var disabled = [];
var disableOptions = function () {
  //console.log(disabled);
    $('option').prop('disabled', false);
    $.each(disabled, function(key, val){
        $('option[value="' + val + '"]').prop('disabled', true);
    });
};

$('.moreAttendence').click(function () {
    var box_html = $('select:first').clone();
    $('.more-box').append('<br />');
    $('.more-box').append(box_html);
    box_html.fadeIn('slow');

    disableOptions();
});

$(document).on('change', 'select', function () {
    disabled = [];
    $('select').each(function(){
        if($(this).val() != 'none'){
            $('option').prop('disabled', false);
            disabled.push( $(this).val() );
        }
    });
    disableOptions();
});

Hope this helps! Let me know if you have any other questions.

Upvotes: 1

Related Questions