ADVERTISEMENT
ADVERTISEMENT

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 »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.