How to create a dynamic SELECT dropdown in JavaSciprt / jQuery?

I want to display all the department names in the Dept table in the combo box. I have a function that retrieves the entire Dept name. How can I dynamically create a combo box at 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 write code that generates (adds) parameters to the list?

+4
source share
5 answers

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 simple 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); } 
+4
source

There is a plugin that already does this, you can check it out. Another advantage of this plugin is that it has built-in autocomplete.

A drop-down list box or a selection field into which you can type text to narrow down the visible set of results. This code is a compilation of the jQuery plugin Autocomplete, as well as other jQuery, and is still in alpha development.

+1
source

A simple and simple JavaScript script will look like this:

 function AddOption(comboBoxID, displayText, displayValue) { var optionItem = document.createElement("option"); optionItem.text = displayText; optionItem.value = displayValue; document.getElementById(comboBoxID).options.add(optionItem); } 
+1
source

You can use the following general 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; } 
+1
source

You can create a new datalist 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 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); 
0
source

All Articles