2016-08-05 46 views
0

我用這個代碼在組合框中添加新值,我的問題是如何設置每個增加的值作爲選擇?默認選中的組合框添加值

<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

爲什麼你要添加的jQuery標記你的問題?它只是JavaScript – Mojtaba

回答

0

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 = ""; 
 
    }
<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>

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>

0

您需要的jQuery此:

option.prop("selected", true);