1

我需要你的帮助。

我有下面的代码,如果在输入框中输入后仅将一个值添加到选择框中(因此,使其成为可编辑的选择框),则效果很好,然后如果在输入框中输入另一个值输入框,选择框的内容变为新输入的值。

我想修改下面的代码,以便允许将其他键入的值添加到选择框中。

<html> 

<style> 

#list { 
    left: expression(this.previousSibling.offsetLeft); 
    width: expression(this.previousSibling.offsetWidth);  
    clip: expression("rect(2px auto 20px " + (this.previousSibling.offsetWidth - 20) + "px)"); 
    overflow: hidden;
    position: absolute;
    top: -1px;
    font-size: 9pt;
    font-family: Arial;
}
#wrapper {
    border: 1px solid blue;
    display: block;
    position: relative;
    width: 180px;
    height: 20px;
}
#text1 {
    border: 0;
    height: 18px;
    width: 180px;
    position: relative;
    font-size: 9pt;
    font-family: Arial;
    padding: 2px;
}
</style> 

<script language="javascript"> 
function getval() {
var select = document.getElementById('list')

    document.getElementById('text1').value = select.options[select.selectedIndex].text

}//end of function

var oNewOption = null;

function AddListItem(oInput) {

var oSelect = oInput.nextSibling;

if (oNewOption == null) {
oNewOption = document.createElement("OPTION");
oSelect.options.add(oNewOption);
}

oNewOption.text = oInput.value;
oNewOption.value = oInput.value;

}

</script> 
<body> 

<div id="wrapper">
<input id="text1" type="text" onkeyup="AddListItem(this)"><select id="list" onchange="getval()"> 
</select>
</div>

</body> 
</html>
4

1 回答 1

0

为了做到这一点,我不得不将 onkeyup 更改为 onchange。因此,只有在输入元素失去焦点后才会添加该选项。

<html> 

<style> 

#list { 
    left: expression(this.previousSibling.offsetLeft); 
    width: expression(this.previousSibling.offsetWidth);  
    clip: expression("rect(2px auto 20px " + (this.previousSibling.offsetWidth - 20) + "px)"); 
    overflow: hidden;
    position: absolute;
    top: -1px;
    font-size: 9pt;
    font-family: Arial;
}
#wrapper {
    border: 1px solid blue;
    display: block;
    position: relative;
    width: 180px;
    height: 20px;
}
#text1 {
    border: 0;
    height: 18px;
    width: 180px;
    position: relative;
    font-size: 9pt;
    font-family: Arial;
    padding: 2px;
}
</style> 

<script language="javascript"> 
function getval() {
var select = document.getElementById('list')

    document.getElementById('text1').value = select.options[select.selectedIndex].text

}//end of function

var oNewOption = null;

function AddListItem(oInput) {

var oSelect = oInput.nextSibling;


oNewOption = document.createElement("OPTION");
oSelect.options.add(oNewOption);


oNewOption.text = oInput.value;
oNewOption.value = oInput.value;
oNewOption.selected = true;

}

</script> 
<body> 

<div id="wrapper">
<input id="text1" type="text" onchange="AddListItem(this)"><select id="list" onchange="getval()"> 
</select>
</div>

</body> 
</html>
于 2013-09-19T18:18:33.073 回答