user3684675
user3684675

Reputation: 381

remove the option selected in one dropdown list field and don't show in other dropdown list present in that row not working- jquery

I have a html table with multiple columns, in two columns i'm displaying the dropdown list. When user selects the value from one dropdown list(Select Product1 or Select Product2 dropdown list), i want to remove the option selected in one dropdown and dont show that option in the other dropdown list...

Below sample code works when the class name is same for all the dropdown list available in the table(Select Product1,Select Product2), but in my case the class name for the dropdown list is same for each colum in the table which breaks the below code.

var $combo = $(".combo");
$combo.on("change", function () {
    var select = this,
        selected = $("option:selected", this).text();

    $combo.each(function (_, el) {
        if (el !== select) {
            $("option", el).each(function (_, el) {
                var $el = $(el);
                if ($(el).text() === selected) {
                    $el.remove();
                }
            });
        }
    });
});

Sample Demo : http://plnkr.co/edit/VSdhVfhyIfI0rV6efrZv?p=preview

In the above demo, when user selects product "laptop" from one dropdown list for one row, the option "laptop" should not be shown in the other dropdown list present in that row...

Upvotes: 0

Views: 987

Answers (1)

charlietfl
charlietfl

Reputation: 171690

Look in same row instead of looping over all the selects in the table. ALso would be simpler to match values

$combo.on("change", function() {
  var $sel = $(this),
       val = $sel.val();

  $sel.parent().siblings().find('.combo option[value=' + val + ']').remove()

});

Note however that you have a different issue also whereby if user changes one that was previously selected you don't have the ability to re-insert one.

Should consider keeping a clone of all the options stored in a variable so you can look for the missing one during subsequent changes

Upvotes: 1

Related Questions