Saturday 9 February 2019

javascript - jQuery: click() not working on elements added by jQuery





I made a to do list using Bootstrap and jQuery. Items get deleted from the list by clicking on the 'X' badge on the right side of each list item. This works for the items that are on the page when it first loads, but you can't remove items that are added by the user.



Maybe something needs to be refreshed to remind the script that new elements should be monitored for the click event?



http://jsfiddle.net/pcx5mvh7/




todo.js:



$(document).ready(function() {
//add item if the button is clicked
$('#addButton').click(function(){
$('
  • X' + $('#input').val() + '
  • ').appendTo('#list');
    $('#input').val(null);
    });

    //add item if the enter key is pressed

    $('#input').bind("enterKey",function(e){
    $('
  • X' + $('#input').val() + '
  • ').appendTo('#list');
    $('#input').val(null);
    });

    $('#input').keyup(function(e){
    if(e.keyCode == 13) {
    $(this).trigger("enterKey");
    }
    });


    //remove an item by clicking the badge
    $('.badge').click(function() {
    $(this).parent().remove();
    });
    });


    index.html:








    To Do List











    To Do List





    • XPushups!


    • XGet Money

    • XIncrease my word power

    • XBeat God at his own game

    • XMake everything go my way






















    Answer



    try this demo: http://jsfiddle.net/enw5rcdx/





    The delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.




    code



       //remove an item by clicking the badge
    $(document).on('click', '.badge', function () {
    $(this).parent().remove();
    });

    No comments:

    Post a Comment

    php - file_get_contents shows unexpected output while reading a file

    I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...