views:

47

answers:

4

I want to display the all the department names in the Dept Table in a combo box. I have a function which fetches all the Dept name. How can i dynamically create combo box in runtime, using javaScript or jQuery.

HTML CODE

     <select id="searchDepartments">
     </select> <input type="button" value="Search" onClick="search();" />

JavaScript function

function getDepartments(){
EmployeeManagement.getDeptList(function(deptList/*contains n-(dept.id, dept.name)*/{
    for(i = 0; i<deptList.length; i++){

How can i able to write a code that generates(adds) options to the list?

+1  A: 

There's a plugin that already does this, you may want to check it out. Another benefit of this plugin, is that it has autocomplete built in.

A drop-down combo box, or a select box into which you can type text to narrow down the visible result set. This code is a compilation of the JQuery Autocomplete plugin as well as other JQuery plugins, and is still in the alpha stage of development.

Robert Greiner
+1  A: 

A plain and simple JavaScript script would look as follows:

function AddOption(comboBoxID, displayText, displayValue)
{
    var optionItem = document.createElement("option");

    optionItem.text = displayText;
    optionItem.value = displayValue;

    document.getElementById(comboBoxID).options.add(optionItem);
}
Kyle Rozendo
+2  A: 

the process is to create and option node for each item in the list, and add it as a child of the select element.

in plain javascript

var sel = document.getElementById('searchDepartments');
var opt = null;

for(i = 0; i<deptList.length; i++) { 

    opt = document.createElement('option');
    opt.value = deptList[i].id;
    opt.innerHTML = deptList[i].name;
    sel.appendChild(opt);
}
lincolnk
+1  A: 

You can use the following generic function:

function addOption(text,value,cmbId) {
    var newOption = new Option(text, value);
    var lst = document.getElementById(cmbId);
    if (lst) lst.options[lst.options.length] = newOption;
}
Zafer