UncleCoder.com

UncleCoder.com

Free programming examples and instructions

Add options to html select

Code and Demo for how to add items in select using javascript

by Athil


Posted on 13 May 2017 Category: Javascript Views: 402

Edited on 09 Aug 2017



DEMO

Hi, Here I am going to show how to add options to HTML select control using Javascript.

Sample Code

var agentdropdown = document.getElementById("SelectAgent");
var opt = document.createElement("option");
opt.text =  "xyz";
opt.value = 1;
agentdropdown.add(opt);
            

In this code, I added dynamically an option in select control. My select control id is 'SelectAgent' And I assigned this control to a variable and then I create an option, Then I added value and text to the option and Finally, I added the option to select control.

Full Code

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Add options to select</title>
</head>
<body>

    <h1>Demo for adding options to select </h1>

    <select id ="SelectAgent">
        <option>-- Select --</option>
    </select>   
    <button type="submit" onclick="AddOption();">Add Option </button>
    <script>
        function AddOption()
        {
            var agentdropdown = document.getElementById("SelectAgent");
            var opt = document.createElement("option");
            opt.text = "xyz";
            opt.value = 1;
            agentdropdown.add(opt);
        }
     </script>
</body>
</html>

 



Leave a Comment:


Advertisement