0

I have 2 code,

This is the First:

    $("#Button1")
    .click(function () {
        var index;            
        var select = $("#DropDownList1");
        var select = document.getElementById("DropDownList1");
        var myindex = ["zero", "one", "two", "three"];
        for (index = 0; index < myindex.length; index++) {
            select.appendChild(new Option(myindex[index]));
        }
    });

This is the Second:

    $("#Button1")
    .click(function () {
        var index;            
        var select = document.getElementById("DropDownList1");
        var myindex = ["zero", "one", "two", "three"];
        for (index = 0; index < myindex.length; index++) {
            select.appendChild(new Option(myindex[index]));
        }
    });

Why the first code doesn't work?

    var select = $("#DropDownList1");

I have to change it to

    var select = document.getElementById("DropDownList1");

I want to turn $("#DropDownList1") to a variable.

0

2 Answers 2

1

appendChild is not a jquery function.

Assuming your first code has a paste-typo with the extra document.getElementById, you can use select.get(0).appendChild() to convert a jquery object to a DOM element.

    var index;            
    var select = $("#DropDownList1");
    var myindex = ["zero", "one", "two", "three"];
    for (index = 0; index < myindex.length; index++) {
        select.get(0).appendChild(new Option(myindex[index]));
    }

or you could continue with jquery, eg:

    for (index = 0; index < myindex.length; index++) {
        select.append("<option>" + myindex[index] + "</option>");
    }
Sign up to request clarification or add additional context in comments.

Comments

1

Thank u for @freedomn-m Now i change my code to this:

        var index;            
        var select = $("#DropDownList1");            
        var myindex = ["zero", "one", "two", "three"];
        for (index = 0; index < myindex.length; index++) {
            select.append("<option>" + myindex[index] + "</option>");
        }

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.