user3472810
user3472810

Reputation: 449

Get input field contents and append to HTML <div> element

I'm trying to get the contents of an input field and add them to my HTML document.

Here's what I have, but it's not working, yet:

            <!DOCTYPE html>
    <html>
        <head>
            <title>To Do</title>
            <link rel="stylesheet" type="text/css" href="stylesheet.css"/>
            <script type="text/javascript" src="script.js"></script>
        </head>
        <body>
            <h2>To Do</h2>
            <form name="checkListForm">
                <input type="text" name="checkListItem"/>
            </form>
            <div id="button">Add!</div>
            <br/>
            <div class="list"></div>
        </body>
    </html>

            $(document).ready(function(){
        var input = $("input[name=checkListItem]");
        $("button").click(function(){
    $("#button").click(function(){   

var toAdd = $('input[name=checkListItem]').val();
    });
            $(".list").append('<div class="item">' + toAdd + '</div>');
        });
    });

Can anyone tell me what I'm doing wrong, please?

Thanks!

Upvotes: 0

Views: 3567

Answers (2)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

you have a few mistakes:

1) $("button") should be $("#button")

2) $("input[name=checkListItem]") should be $("input[name='checkListItem']")

3) put var input = $("input[name='checkListItem']").val(); inside click event

and do like this:

$(document).ready(function(){

    $("#button").click(function(){

       var input = $("input[name='checkListItem']").val(); 
       // .val() will give textbox value

       $(".list").append('<div class="item">' + input + '</div>');
     });

});

Fiddle Example

or more simply:

$(document).ready(function(){

   $("#button").click(function(){

    $(".list").append('<div class="item">' + $("input[name='checkListItem']").val()+ '</div>');

   });

});

Upvotes: 2

Cl&#233;ment Andraud
Cl&#233;ment Andraud

Reputation: 9269

$(document).ready(function(){
    var input = $("input[name=checkListItem]").val();
    $("#button").click(function(){
        $(".list").append('<div class="item">' + input + '</div>');
    });
});

button is a div, not a html element, so add #

Upvotes: 0

Related Questions