kws3778
kws3778

Reputation: 317

jQuery append div on click

So I'm making this thing in jQuery where if the user clicks a button a div appears and asks the user to enter some notes(basically a sticky note feature).

The HTML and CSS are done correctly, the only problem is that the jQuery won't work:

    $(document).ready(function() {
    $("#top-tabs ul li").hover(function() {
        $(this).find("ul>li").stop().fadeToggle(400);
    });

    $("#submitpnote").on("click", function() {
        $("body").append("<div id='pnoteprompt'><input id ='input-pnote'type='text' placeholder='your note title'></input><input id ='input-pnote-p'type='text' placeholder='your note'></input><button id=confirmpnote>confirm note</button></div>");
        $("#pnote-prompt").fadeTo(100, 1);

    });

    $("#confirmpnote").on("click", function() {
        var $pnotetitle = document.getElementById("input-pnote").value;
        var $pnotep = document.getElementById("input-pnote-p").value;
        $("#pnotes-list").append("<div class='pnote-title'><li>" + $pnotetitle + "<br>" + $pnotep + "</li></div>");
        $("#pnoteprompt").remove();
    });

});

The js jQuery file is linked properly. It's just that in the submitpnote function(the second on), the div doesn't append. I click the button and nothing appears on my screen. I've tried putting some prompt() debuggers and the method is running but the div doesn't seem to be appending.

Does anyone know why this is happening? Thanks!

Upvotes: 0

Views: 2005

Answers (2)

Dhiraj
Dhiraj

Reputation: 33618

Looks like you are adding the container that has submitpnote button dynamically so you would have to add the even handler using .on()

$('body').on('click', '#submitpnote', function(e){
  $(e.delegateTarget).append("<div id='pnoteprompt'><input id ='input-pnote'type='text' placeholder='your note title'></input><input id ='input-pnote-p'type='text' placeholder='your note'></input><button id=confirmpnote>confirm note</button></div>");
  $("#pnote-prompt").fadeTo(100, 1);
});

Upvotes: 0

Kevin Grabher
Kevin Grabher

Reputation: 399

As I see it confirmpnote is dynamically created content, so you can't do $(#confirmnote) since that won't exist at the point that code is executed.

For dynamically created content use:

(document).on('click', 'selector', function(){
 //to stuff
});

selector would be #confirmpnote for example

Upvotes: 1

Related Questions