0

live example of project: http://jsfiddle.net/k3buckuc/

enterItem = []
itemNumber = 0

// mark item as checked and add delete functionality 
function check() {
    $('#itemsListed').on('click', 'li', function() {    
        $(this).toggleClass('checked');
        $(this).append('<hr />');
        $(this).append('<button class="trash">X</button>');
        $(this).not('.checked').find('hr').remove();
        $(this).not('.checked').find('button').remove();
        // enable trash or delete functionality individual list items
        $('.trash').on('click', function() {
            $(this).closest('li').remove();
        });
    });
}

this only executes properly when itemNumber is odd, or when enterItem contains an odd number of items

see the fiddle to check how I am pushing items into the array and my increment technique

troychroi
  • 49
  • 1
  • 9
  • That code doesn't use `enterItem` or `itemNumber` at all, so it can't reasonably be affected by what those variables contain. What does "executes propertly" mean, i.e. what happens, and how does that differ from what's expected? – Guffa Aug 24 '14 at 23:00
  • check out the fiddle ... I couldn't add everything in the post. it is supposed to add a css class of 'checked' and enable a button that can remove it if it is checked. but it only works if there are an odd number of items in enterItem – troychroi Aug 24 '14 at 23:02

2 Answers2

1

That's because you are binding the same event over and over. Each time that you add an item another handler is bound for the click event.

When you have added an even number of items there is an even number of event handlers added. When you click an item the second handler will undo what the first handler did.

When you have for example ten items, the event handler will be called ten times. As the end result is the same as if the event handler was called zero times, it appears as nothing is happening.

Just bind the event handler once, not every time that you add an item.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

Just do this:

 //   function check() {
        $('#itemsListed').on('click', 'li', function() {    
            $(this).toggleClass('checked');
            $(this).append('<hr />');
            $(this).append('<button class="trash">X</button>');
            $(this).not('.checked').find('hr').remove();
            $(this).not('.checked').find('button').remove();
            // enable trash or delete functionality individual list items
            $('.trash').on('click', function() {
                $(this).closest('li').remove();
            });
        });
   // }

Move the bind outside the check() function;

Radu Andrei
  • 1,075
  • 10
  • 19