Dynamic combobox-listbox-drop-down using javascript

文章源自:http://viralpatel.net/blogs/dynamic-combobox-listbox-drop-down-using-javascript/

Dynamic combobox-listbox-drop-down using javascript

Want to populate dynamically combobox-listbox-drop-down using javascript? Let us see a very simple script to do this. First let us see createElement() of document object in javascript.

//Create a table element dynamically
var table = document.createElement("table");
 
//Create a select element dynamically
var select = document.createElement("select");
 
//Create a option element dynamically
var option = document.createElement("option");

 Thus, createElement method takes a parameter which is the string that specifies the name for the element node and returns the element node.

Let us see how can we populate a dropdown or combobox using this method. Following is the html file of our example:

<HTML>
    <HEAD>
        <TITLE>Dynamically populating drop down, combobox, list box using JavaScript</TITLE>
        <SCRIPT language="javascript" src="config.js"></SCRIPT>
    </HEAD>
    <BODY style="font-family: sans-serif">
 
        <fieldset>
            <legend>Combo box</legend>
            Add to Combo: <input type="text" name="txtCombo" id="txtCombo"/>
            <input type="button" value="Add" οnclick="addCombo()">
            <br/>
            Combobox: <select name="combo" id="combo"></select>
        </fieldset>
    </BODY>
</HTML>

 And following is the javascript file:

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;
    try {
        combo.add(option, null); //Standard
    }catch(error) {
        combo.add(option); // IE only
    }
    textb.value = "";
}

 Thus, when we provide a value in text box and click the Add button, a new option element is created using document.createElement method. The attributes of the option element are set using the method .setAttribute(). And finally the option is added to combo using .add() method.



 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值