Shermaine Chaingan Shermaine Chaingan - 3 months ago 12
Javascript Question

default selected combobox in added value


i used this code for adding new value in combobox, my problem is how
will i set every added value as selected?


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

Answer

 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>

Comments