user2932587
user2932587

Reputation:

Adding items to a list when a button is pressed in Javascript

I am creating a page that has an unordered list of items with the id "faves", a text box with the id "add", and a button with the id "btnAdd". By default the list contains 3 items, but the user is supposed to be able to enter text into the text box, click the button, and whatever they typed into the text box should be added to the list. I can't seem to figure out how to get the text entered to display in the list when the button is clicked.

Here is my HTML, this also includes the CSS and Javascript:

<html>
    <head>
        <title>Project 1 Tanner Taylor</title>
        <h1>Project 1 Tanner Taylor</title>
        <style type="text/css">
            #clickMe {
                background-color: blue;
                border: 2px double black;
                font-size: larger;
            }
            @media (max-width: 299px) {
                #faves {
                    color: red;
                }
            }
            @media (max-width: 500px) and (min-width: 300px) {
                #faves {
                    color: blue;
                }
            }
            @media (min-width: 501px) {
                #faves {
                    display: none;
                }
            }
        </style>
        <script type = "text/javascript">
            function clickMe() {
                document.getElementById("clickMe").innerHTML="Ouch!";
            }
        </script>

    </head>
    <body>
        <div id="clickMe" onclick="clickMe()">
            Click Me!
        </div>
        <div>
        <ul id="faves">
            <li>Video Games</li>
            <li>Food</li>
            <li>Sleeping</li>
        </ul>
        <input type="text" id="add" size ="50"/>
        <input type="button" id="btnAdd" value="Add" onclick=/>
        </div>
    </body>
</html>

Would anybody be willing to point me in the right direction?

Upvotes: 2

Views: 21683

Answers (1)

Johan Karlsson
Johan Karlsson

Reputation: 6476

Try this:

<script>
    function addItem(){
        var li = document.createElement("LI");  
        var input = document.getElementById("add");
        li.innerHTML = input.value;
        input.value = "";

        document.getElementById("faves").appendChild(li);
    }
</script>

<input type="button" id="btnAdd" value="Add" onclick="addItem()">

Upvotes: 4

Related Questions