Looping to set dropdown values – jquery object ref eror

I am not really using the jQuery way of setting the value & text of this dropdown. I’m not quite sure the jQuery way to set this, however the ref to the dropdown is definitely a jQuery object representing the dropdown.

So my variable holding the jQuery object that is referencing (represending) the dropdown is defined like this:

ddlCar = $ ('#<%=ddlCar.ClientID %>'); // yes this is referencing an ASP.NET control id

ddlCar works fine in terms of referencing the dropdown…that’s not the issue.

Now here’s the code throwing an error and my initial problem:

for (key in carList)
{
    ddlCar[0].options[i].text = carList[key].Name;
    ddlCar[0].options[i].value = carList[key].CarId;
    i++;
}

Error is: ddlCar[0].options[i] is undefined

Keep in mind this loop worked when I was referencing the dropdown using standard JS code with getElementByID but now I’m referencing the dropdown through a jQuery object ddlCar and so now the loop broke after changing my ddlCar to ref the dropdown through a jQuery object (using $ (‘#<%=ddlCar.ClientID %>’);`).

So for now, I kinda tried to hack this to work. I know that adding [0] now will allow me to reference dropdown ref which is a jquery object as though it is a RAW DOM element so that I can use it like plain old JS syntax. But for some reason, I still get undefined for ddlModel[0].options[i]. I know that ddlModel[0] is a valid object because I’ve used it like this in other parts of my code on the page:

ddlCar[0].options.length = ObjectCount(carList);

So I am curious why this loop is not working first and foremost. I even tried this:

for (key in carList)
{
    ddlCar[0].options[0][i].text = carList[key].Name;
    ddlCar[0].options[0][i].value = carList[key].CarId;
    i++;
}

And I guess last this is kinda a 2-part question.

What would be the jQuery way of setting the text and value of my dropdown? I’ve already got a jQuery object ref to the dropodown so naturally I’m gonna refactor this later not to use JS for the rest of the syntax to set the values.

newest questions tagged jquery – Stack Overflow

About Admin