Best way to create a dynamic Select (Dropdown) list?

Brad8118 picture Brad8118 · Feb 27, 2009 · Viewed 11.6k times · Source

I'm using jQuery and jqGrid.

I'm trying to populate a select list dynamically, one for each row and I need to add a click event to it. When the select list is being populated I grab the index of the item I want selected, and then after all items are add I'm trying to set the selected item.

I've tried

$("#taskList")[0].selectedIndex = taskIndex;
$("#taskList").selectOptions(taskIndex, true);
$("#taskList").val(1); //Tried to see if I could select any index and no luck.
$("#taskList option[value=" + taskIndex + "]").attr("selected", true);

So this means I'm probably populating the list incorrectly...

var taskList = document.createElement("select");
var taskIndex = 0;
for (var i = 0; i < result.TaskTypes.length; i++) {
   $(taskList).addOption(result.TaskTypes[i].TaskId, result.TaskTypes[i].TaskName);
   if (result.TaskTypes[i].TaskName == rowData.TaskType)
    taskIndex = i;
}

Is there a better way?

I tried this but I couldn't add the click event to it. The proper item was selected though.

var taskList = "<select name='taskList' Enabled='true'>";
for (var i = 0; i < result.TaskTypes.length; i++) {
    if (result.TaskTypes[i].TaskName == rowData.TaskType)
        taskList += "<option selected> " + result.TaskTypes[i].TaskName + "</option>";
    else
    taskList += "<option>" + result.TaskTypes[i].TaskName + "</option>";
}
taskList += "</select>";

Answer

Guss picture Guss · Feb 27, 2009

The way I would have done it, is in your first example - instead of using the jQuery API for addOption, use the DOM API, like this:

var option = document.createElement("option");
option.innerHTML = result.TaskTypes[i].TaskName;
option.value = result.TaskTypes[i].TaskId;
option.onclick = myClickHandler;
taskList.add(option, null);

Then after the loop you can just use:

taskList.selectedIndex = taskIndex;

to have the select list positioned to your required default selection.

I haven't used jQuery extensively, but I think its a good idea not to neglect the DOM API - its often not as convenient as the shortcuts that jQuery and other libraries offer, but these extend DOM capabilities and should not come instead of the DOM.