Salomo Panjaitan Salomo Panjaitan - 1 month ago 6
ASP.NET (C#) Question

ASP.NET Dropdownlist into jquery variabel

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

Answer

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>");
    }
Comments