1

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...

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.