JavaScript - Add user entered item into ListBox

In this code snippet we will enter an item and will insert it into ListBox.

Add User Entered Item into ListBox

JavaScript function:

<script type="text/javascript">
    function insertItemIntoListBox() {
        var x = document.getElementById("access");
        var item = document.getElementById("txtItem").value;
        var option = document.createElement("option");
        option.text = item;
        x.add(option);
        alert(item + " has been added.");
    }
</script>

HTML Source Code with JavaScript:

<!--JavaScript – Add user entered item into ListBox.-->
<html>
    <head>
        <title>JavaScript - Add user entered item into ListBox.</title>
        <script type="text/javascript">
            function insertItemIntoListBox() {
                var x = document.getElementById("access");
                var item = document.getElementById("txtItem").value;
                var option = document.createElement("option");
                option.text = item;
                x.add(option);
                alert(item + " has been added.");
            }
        </script>
    </head>
    <body style="text-align: center;">
        <h1>JavaScript - Add user entered item into ListBox.</h1>
        <form>
            <p><big>Enter your favourite accessory: </big></p>
            <p><input type="text" id="txtItem" /></p>
            <p><input type="button" onclick="insertItemIntoListBox()" value="Insert" /></p>
            <select id="access" size="10">
                <option>Mobile</option>
                <option>Tablet</option>
            </select>
        </form>
    </body>
</html>

Result:

add item into listbox using javascript

JavaScript Examples »



Related Examples



All JavaScript Examples

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.