的问题:
onblur
我输入 [通过使用onkeyup而不是onchange解决] 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;
}
这是最终的工作代码:
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);
}
}
答案 0 :(得分:1)
要在用户输入时检测更改,您必须使用onkeypress
事件。这里已经回答了类似的问题:Detecting "value" of input text field after a keydown event in the text field?
答案 1 :(得分:1)
对IE使用onpropertychange(这也会在剪切/粘贴时触发)
此外:您应该使用new Option()
来创建和插入选项,而不是操作innerHTML。