DS9 DS9 - 7 months ago 16
PHP Question

How to populate a dropdown using unselected options from other dropdowns?

I use JQuery Steps.In 1st and 2nd step, i have a dropdown with multiple select option.

<select name="numbers" id="numbers">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>


in step2(same as step1 but with diff. purpose)

<select name="allocate_numbers" id="allocate_numbers">
<option value="1">1</option>
: : :
</select>


now i have a 3rd dropdown in 3rd step.Here i want selectbox like..suppose user select
1,2
in step1,
3,4
in step2.

now,i want selectbox that contain only
5,6
in step3.

How to do that?

side note: I done validation to prevent duplicate entry for step1 and step2 dropdown.
means if user select 1,2 in step1 then he can not select 1,2 in step2.
I don't find suitable title for my quetion so feel free to edit it.

Answer

Updated and better answer:

The solution turns out to be rather simple. Find all unselected options in first dropdown and filter those that are not selected in other dropdowns. Add event delegation and the result is:

$(document).on("change", ".numbers", function () {
    $("#select1").empty();
    $(".numbers:eq(0) option:not(:selected)").filter(function () {
        return $(".numbers:gt(0) option[value=" + this.value + "]:selected").length === 0
    }).clone().appendTo("#select1");
});

Demo here

Original answer:

This turned out to be a real brain twister. Basically you need to:

  1. Prepare combined list of selected values
  2. Iterate over options from both lists
  3. Filter options that are not selected
  4. Filter duplicates
  5. Clone and append

Here is my go at it but there is probably a simpler solution:

$("#numbers, #allocate_numbers").on("change", function () {
    $("#select3").empty();
    var selectedValues = [],
        renderedValues = [];
    $.merge(selectedValues, $("#numbers").val() || []);
    $.merge(selectedValues, $("#allocate_numbers").val() || []);
    $("#numbers option, #allocate_numbers option").filter(function () {
        if ($.inArray(this.value, selectedValues) === -1) {
            if ($.inArray(this.value, renderedValues) === -1) {
                renderedValues.push(this.value);
                return true;
            }
        }
        return false;
    }).clone().appendTo("#select3");
});

Demo here