5

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?

5 Answers 5

6

The process is to create an 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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

U could declare the opt var inside the for loop
1

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.

Comments

1

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

Comments

1

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;
}

Comments

0

You can create a datalist new option in html5:

<input type="text" class="form-control" id="your_id" list="your_list" 
placeholder="Status"/>
<datalist id="your_list">
</datalist>

and fill it with a jquery .append function:

for(var i=0, len=resultado.response['id'].length; i<len; i++) 
{
    list += '<option value="' +resultado.response['data'][i]+" ( "+resultado.response['id'][i]+" ) "+ '"></option>';
}
dataList.html(list);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.