Seach for option in HTML Select
Seach for option in HTML Select
HTML
Search <input type="text" ID="searchFor" onkeyup="searchSelect(this.id,'searchIn')">
<br />
<select id="searchIn" size="3" multiple> </select>
JavaScript
window.onload = function () {
setOptions("searchIn");
};
var jsonObj = {};
jsonObj = {"group1":
{"option1":"Option 1",
"option2":"Option 2"},
"group2":
{"option3":"Option 3",
"option5":"Option 5",
"option7":"Option 7"}
};
function setOptions(searchInID) {
var theSelect = document.getElementById(searchInID);
for (var key in jsonObj) {
// set option groups
var optionGroup = document.createElement("optgroup");
optionGroup.label = key;
for (var key1 in jsonObj[key]) {
// set options
var option = document.createElement("option");
option.value = key1;
option.text = jsonObj[key][key1];
option.label = jsonObj[key][key1];
optionGroup.appendChild(option);
}
theSelect.appendChild(optionGroup);
}
}
function searchSelect(searchForID, searchInID) {
var input = document.getElementById(searchForID).value.toLowerCase();
var theSelect = document.getElementById(searchInID);
theSelect.innerHTML = '';
for(var key in jsonObj) {
var optionGroup = document.createElement("optgroup");
optionGroup.label = key;
for(var key1 in jsonObj[key]) {
if(jsonObj[key][key1].toLowerCase().indexOf(input) >= 0) {
var option = document.createElement("option");
option.value = key1;
option.text = jsonObj[key][key1];
option.label = jsonObj[key][key1];
optionGroup.appendChild(option);
}
}
theSelect.appendChild(optionGroup);
}
}