0

I'm making a todo-list where the tasks are pushed into an array, then the array is rendered by looping over all the tasks in a for loop.

For every task, I want to bind a delete button so that particular task is removed. As the code is now, no item is removed because the last value after the loop has finished is returned.

I know I need some kind of closure , but I don't know how to succeed with this.

My markup is as follows:

<div class="row">
        <div class="medium-8 medium-centered columns">
            <div class="todo-container">
                <h2>Todo-list</h2>
                <input type="text" id="todo-input" placeholder="Hit enter to add new" autofocus>

                <div class="all-posts">

                </div>
            </div>
    </div>

And Javascript + jQuery:

(function($, window, undefined) {

        var tasks = [],
        todoInput = $("#todo-input");


        todoInput.on('keypress', function(e) {
            if (e.keyCode == 13) {
                createTask();
            }
        });

        function createTask() {
            var input = todoInput.val();

            if (input.length !== 0) {
                tasks.push(input);
            }

            todoInput.val("");

            renderTasks();
        }

        function renderTasks() {
            var allPosts = $(".all-posts");
            allPosts.empty();

            for (var i = 0; i < tasks.length; i++) {
                allPosts.append('<div class="single-post clearfix"><input id="checkbox" type="checkbox"><p>' + tasks[i] + '</p><a href="#" class="button alert delete-button">Delete</a></div>');

                $(".single-post").unbind("click").on("click", ".delete-button", function() {
                    console.log(i);
                    deleteTask(i);
                });

            }
        }

        function deleteTask(i) {
            console.log(i);
            tasks.splice(i, 1);

            renderTasks();
        }


    })(jQuery, window);

The code is best viewed at http://jsfiddle.net/ymvhwzsf/4/ at row 32

Filip Nilsson
  • 407
  • 7
  • 20
  • possible duplicate of [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Teemu Feb 15 '15 at 19:38
  • You'd have better to delegate event: http://learn.jquery.com/events/event-delegation/ **As a side note** You rendered HTML markup once more than one task is added is invalid, IDs ***must*** be unique on document context – A. Wolff Feb 15 '15 at 19:38

1 Answers1

1

In our case, better use event delegation, like this

$(".all-posts").on("click", ".single-post .delete-button", function() {
    deleteTask($(this).data('id'));
});

And for link add data attribute

data-id="' + i + '"

Example

Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144