0

I am building a simple shopping list. Currently my code will delete an added list item when you click anywhere on the list item itself, I would like it to work where clicking on the UI button next to it will delete the entire item from the list, what I have tried will only delete the UI button itself. Thanks for the help, I am very much a novice

HTML

<div id="list">
    <ul class="shopping"></ul>
</div>

jQuery

$(document).ready(function () {
function addItemToList(e) {
    var addItem = $('#item').val();
    $('.shopping').append('<li>' + '<button class="uibutton"></button>' + addItem + '</li>');
    $('.uibutton').button({
        icons: {
            primary: "ui-icon-heart"
        },
        text: false
    });
    $('ul').on('click', 'li', function() {
    $(this).remove();
});
    $('#item').val('');
}

/*adds list item to list when cart icon is clicked, clears #item input field*/
$('#toadd').click(function (e) {
    addItemToList(e);
});

/*adds list item to list when enter key is hit, clears #item input field*/
$('#item').keydown(function (e) {
    if (e.which == 13) {
        addItemToList(e);
    }
});

});

1 Answer 1

1

You can make 2 changes like

$(document).ready(function () {
    function addItemToList(e) {
        var addItem = $('#item').val();
        var $li = $('<li>' + '<button class="uibutton"></button>' + addItem + '</li>').appendTo('.shopping');

        //target only newly added button
        $li.find('.uibutton').button({
            icons: {
                primary: "ui-icon-heart"
            },
            text: false
        });
        $('#item').val('');
    }

    //use event delegation instead of adding the handler in another event handler... 
    $('ul.shopping').on('click', '.uibutton', function () {
        $(this).closest('li').remove();
    });

    /*adds list item to list when cart icon is clicked, clears #item input field*/
    $('#toadd').click(function (e) {
        addItemToList(e);
    });

    /*adds list item to list when enter key is hit, clears #item input field*/
    $('#item').keydown(function (e) {
        if (e.which == 13) {
            addItemToList(e);
        }
    });
});

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.