Paul
Paul

Reputation: 209

Changing a newly appended element in JQuery

So when I check the original boxes off, they disappear. But when you switch lists and the new checkbox appears, when you check it it does not disappear. Why?

EDIT: I made changes to the code to reflect the answer. I am wondering now why the the textbox there by default deletes when pressing enter, but the new one that appears does not?

$(document).ready(function() {
    
    $(document).on("click",".items",function() {
        $(this).remove();
    });
    
    $("li").click(function () {
        $("li").removeAttr("class");
        $(this).attr("class","selectedlist");
        $(".items").remove();
        $("#itemsbar").append('<div class=\"items\" id=\"c1div\"><input type=\"checkbox\" id=\"c1\" name=\"c1\" /> \
        <label for=\"c1\"><span></span>New Box~</label></div>');
    });
    
    $("#itemsbar > p").click(function () {
        $(this).remove();
        $("#itemsbar").append('<input class=/"addnew/" type=/"text/"></input>');
    });
    
    $(document).on("keyup",'.addnew', function (e) {
        if (e.which == 13) {
            $(this).remove();
            e.preventDefault();
        }
    });
    
});
<div id="main">
    <div id="listsbar">
        <h1>To Do List</h1>
        <ul id="lists">
            <li id="l1" class="selectedlist">Test List</a></li>
            <li id="l2">Test List 2</a></li>
        </ul>
    </div>
    <div id="itemsbar">
        <div class="items" id="c1div"><input type="checkbox" id="c1" name="c1" />
        <label for="c1"><span></span>Check Box 1</label></div>
        <div class="items" id="c2div"><input type="checkbox" id="c2" name="c2" />
        <label for="c2"><span></span>Check Box 2</label></div>
        <p>Click to Add</p>
        <input class="addnew" type="text"></input>
    </div>
</div>

Upvotes: 1

Views: 1483

Answers (1)

ajmajmajma
ajmajmajma

Reputation: 14216

Change

$(".items").click(function () {

to

 $(document).on("click",".items",function() {

You are binding on the document ready to the items that are on the document, so when you bring a new item on, it does not have this listener bound to it.

Upvotes: 3

Related Questions