suyog patil
suyog patil

Reputation: 414

appending array of option object to multiple selects

I am trying to append array of option objects to two select tag. But it appends to second select tag only.

<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<select id="select1"></select>
<select id="select2"></select>
<script>
    var options = [];
    var option1 = new Option("1", "1");
    options.push(option1);
    var option2 = new Option("2", "2");
    options.push(option2);
    var option3 = new Option("3", "3");
    options.push(option3);
    $("#select1").append($(options));
    $("#select2").append($(options));
</script>

If I use only one select to append options it works. But for more than two it wont. It appends to last one only. Please help to resolve this...

Upvotes: 1

Views: 96

Answers (2)

JsCoder
JsCoder

Reputation: 1733

Alternatively you can make a step further and create a function populating your selects with data, something like:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
    <select id="select1"></select>
    <select id="select2"></select>

    <script>
        $(function () {
            var selectData = [{ id: "1", text: "1" }, { id: "2", text: "2" }, { id: "3", text: "3" }];

            var bindSelect = function (args) {
                var data = args.data;
                var $select = args.select;

                $select.append(data.map(function (item) { return new Option(item.id, item.text); }));
            };

            $("#select1, #select2").each(function () {
                bindSelect({ data: selectData, select: $(this) });
            });

        });
    </script>
</body>
</html>

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

Your code is working. What happens is that it first appends the options to #select1 however because it is a reference variable the same options are then moved to #select2.

To solve this you need to clone the options to make a copy of them to add to the second select:

$("#select1").append($(options));
$("#select2").append($(options).clone());

Example fiddle

Upvotes: 5

Related Questions