Roka
Roka

Reputation: 514

Jquery add to dropdown list

I have three dropdown lists. When a selection is made from dropdown list 1, I want to remove that option from the other two. When dropdown list 1 changes it selection, add back the previous and remove the currently selected. This is the following code that I have. I feel I'm close, but still missing something essential.

<script>
    $(document).ready(function () {
        $("#option1dropdown").change(function () {
            $("#option2dropdown").empty();
            $("#option3dropdown").empty();
            $("#option1dropdown option").each(function(){
                if ($("#option1dropdown").val() != this) {
                    $("#option2dropdown").append(this);
                    $("#option3dropdown").append(this);
                }
            });
        });
    });
</script>

Upvotes: 0

Views: 44

Answers (1)

Steve0
Steve0

Reputation: 2243

Append will move, not copy the element in question. You should also double check your comparison within the if.

$(function () {
    $("#option1dropdown").change(function () {
        $("#option2dropdown").empty();
        $("#option3dropdown").empty();
        $("#option1dropdown option").each(function(idx, item){
            if ($("#option1dropdown").val() != $(item).val()) {
                $("#option2dropdown").append($(item).clone());
               $("#option3dropdown").append($(item).clone());
            }
        });
    });
});

https://jsfiddle.net/egeLh428/

Upvotes: 2

Related Questions