我使用此代码在组合框中添加新值,我的问题是如何 我会将每个附加值设置为选中吗?
<legend>Combo box</legend>
Add to Combo: <input type="text" name="txtCombo" id="txtCombo"/>
<input type="button" value="Add" onclick="addCombo()">
<br/>
Combobox: <select name="combo" multiple id="combo"></select>
</fieldset>
</BODY>
</HTML>
<script>
function addCombo() {
var textb = document.getElementById("txtCombo");
var combo = document.getElementById("combo");
var option = document.createElement("option");
option.text = textb.value;
option.value = textb.value;
option.value = textb.value;
try {
combo.add(option, null ); //Standard
}catch(error) {
combo.add(option); // IE only
}
textb.value = "";
}
</script>
答案 0 :(得分:1)
试试这个。我已添加combo.selectedIndex = combo.options.length-1;
来计算所有选项并选择最高值。你必须减少它,导致索引计数为零。
<legend>Combo box</legend>
Add to Combo: <input type="text" name="txtCombo" id="txtCombo"/>
<input type="button" value="Add" onclick="addCombo()">
<br/>
Combobox: <select name="combo" multiple id="combo"></select>
</fieldset>
</BODY>
</HTML>
<script>
function addCombo() {
var textb = document.getElementById("txtCombo");
var combo = document.getElementById("combo");
var option = document.createElement("option");
option.text = textb.value;
option.value = textb.value;
option.value = textb.value;
try {
combo.add(option, null ); //Standard
combo.selectedIndex = combo.options.length-1;
}catch(error) {
combo.add(option); // IE only
}
textb.value = "";
}
</script>
&#13;
答案 1 :(得分:0)
gdi32
function addCombo() {
var textb = document.getElementById("txtCombo");
var combo = document.getElementById("combo");
var option = document.createElement("option");
option.text = textb.value;
option.value = textb.value;
option.value = textb.value;
option.selected = true;
try {
combo.add(option, null ); //Standard
}catch(error) {
combo.add(option); // IE only
}
textb.value = "";
}
答案 2 :(得分:0)
你需要jQuery:
option.prop("selected", true);