在输入框中键入其他选项值后,将其他选项值添加到选择框中

Adding additional option values to the selectbox after they are typed in the input box

本文关键字:其他 选项 添加 选择 输入      更新时间:2023-09-26

我需要你的帮助。

我在下面有以下代码,如果在输入框中键入一个值后仅将一个值添加到选择框中(因此,使其成为可编辑的选择框),那么如果在输入框中键入另一个值,则选择框的内容将更改为新输入的值。

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

<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>

为了做到这一点,我不得不将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>