Issues:
- In Chrome and Firefox the code works but the event is fired
onblurand I need it when typing [solved by usingonkeyupinstead ofonchange] - This is not working in IE at all! [solved by using Option object, see the update..]
HTML:
<input type="text" onchange="getLocations(this)" />
<select size="6" multiple="multiple" id="locationOpt"></select>
JavaScript:
function getLocations(element) {
var locations = Array("red","green","blue");
var location_matched = [];
for ( i in locations ){
if(locations[i].search(element.value) > -1){
location_matched.push(locations[i]);
}
}
var html = "";
for( i in location_matched){
html += "<option value =\"" + i + "\">" + location_matched[i] + "</option>";
}
document.getElementById("locationOpt").innerHTML = html;
}
Update
This the final working code:
HTML:
<input type="text" onkeyup="getLocations(this)" />
<select size="6" multiple="multiple" id="locationOpt"></select>
JavaScript:
function getLocations(element) {
var locations = Array("red","green","blue");
var location_matched = [];
for ( i in locations ){
if(locations[i].search(element.value) > -1){
location_matched.push(locations[i]);
}
}
var optionList = document.getElementById("locationOpt");
//to remove all options
while (optionList.options.length) {
optionList.remove (0);
}
for( i in location_matched){
// Option (text, value)
var locationOption = new Option (location_matched[i], i);
optionList.options.add (locationOption);
}
}
Use onpropertychange for IE(this will also fire on cut/paste).
Furthermore: Instead of manipulating the innerHTML you should use
new Option()to create and insert the options.