UncleCoder.com

UncleCoder.com

Free programming examples and instructions

Add options (Items) to html select using javascript

Demo and code for how to add more options (list item) in html select control using javascript

by Athil


Posted on 27 Jul 2018 Category: Javascript Views: 38

Edited on 28 Jun 2019


Here I am going to show how to add items dynamically in HTML select control using javascript.

DEMO

Script

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

 

Where "SelectAgent" is the name of select control and opt is the new option with value "1" and text "xyz".

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