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
 
    