Johny
Johny

Reputation: 387

jQuery, Filling DropDown list

I have 2 dropdown lists on my page created dynamically in a loop (for 1 to 2), on change event of 1 (onChange= fillDropDown(this, <%=i%>);), I'm trying to fill up the second dropdown list. code as follows:

function fillDropDown(control, id) {
    var ddllist = $("#dropDownList"+ id); // Debug : OK 
    var url = "GetData.asp?param=" + $(control).val(); // Debug : OK
    $.getJSON(url, function (data){
        $.each(data, function(){
            // database call is successful, I had alert here to display the data rows.
            ddllist .append($("<option />").val(this.ID).text(this.Name));
        });
    });
}

I was using pure JS before by getting the element using document.getElementById("dropDownList" + id), then in a for loop, creating a new element (option), assigning its innerHTML and value attributes with data and finally appending this element to the dropdown ddlInstType.appendChild(element). This works fine, but only in IE. for some reasons, this solution doesn't work in Firefox & Chrome. I tried moving the script at the bottom of my page as well, still no go.

This problem may have been discussed here before multiple times and I did search for possible answers, But couldn't fix my issue. I'm not sure what am I doing wrong.

Thank you in advance and if you need more info, I'd be prompt to provide it.

PS: No errors thrown, it just doesn't do anything at all. My second dropdown remains empty.

EDIT 2:

Since the original code was written by someone else, this second dropdown was missing an ID attibute, only name attribute was assigned. Added ID attribute as same as the name and it works great now. For some strange reasons, document.getElementById() worked in IE, even thou ID wasn't there. But didn't work in Chrome & Firefox. and because it worked in IE, i kinda ignored the possibility of syntax being wrong.

Upvotes: 0

Views: 167

Answers (1)

Tez Wingfield
Tez Wingfield

Reputation: 2251

Without seeing all of the code it's hard to simulate the problem. I have a similar function in one of my apps.

    //Extract from ajax function
    $.each(data.d, function (index, element) 
       {
        users += "<option data-u-i='" + element.uid + "'>" + element.firstName + " " +     
                  element.lastName + "</option>";
       });

I then pass the users variable into the dropdown:

$('.dropdown').html(users);

Hope this helps.

Regards,

Upvotes: 1

Related Questions