How to create a dynamic SELECT drop-down list in JavaScript/jQuery?
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(f开发者_如何学Cunction(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?
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);
}
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.
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);
}
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;
}
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);
精彩评论