Exercise - jQuery AJAX - Peter's

Todo handling

by Jennifer Piccione

HTML

<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<div class="container">
     <h2>Todos</h2>

    <p> <a id="all" href="#">Load All Items</a>

        <br/> <a id="incomplete" href="#">Load Incomplete Items</a>

    </p>
    <form>
        <ul id="items"></ul>
    </form>
</div>

CSS

.completed {
    text-decoration: line-through;
}

JavaScript

// Ajax with jQuery
// We will be using this service to fetch data
// This server is friendly enough to be CORS:*
//     http://jsonplaceholder.typicode.com/
// if we have trouble with that, we can do this on
// local servers fetching up static .json data
//

// Part 1
// Make a JSON request to
//     http://jsonplaceholder.typicode.com/todos
// Load the data from here and build a ul/li of TODO items
// Each todo items should display at least its title
// Hint: filter by a userId to limit the data, ?userId=5

$(function () {
    var items = $("#items");
    var allItemsURL = 'http://jsonplaceholder.typicode.com/todos?userId=5';
    var incompleteItemsURL = 'http://jsonplaceholder.typicode.com/todos?completed=false&userId=5';

    var fetchItems = function (url) {
        $.getJSON(url, function (response) {
            items.empty();
            $.each(response, function () {
                var li = $("<li></li>");
                var cb = $("<input type='checkbox'/>");

                li.text(this.title);
                li.prepend(cb);

                if (this.completed) {
                    li.addClass("completed");
                    cb.prop("checked", true);
                }

                items.append(li);
            });
        });
    };

    $("#all").click(function (e) {
        e.preventDefault();
        fetchItems(allItemsURL);
    });

    $("#incomplete").click(function (e) {
        e.preventDefault();
        fetchItems(incompleteItemsURL);
    });
    
    items.on("click", "input:checked", function(e) {
       $(e.target).parent().fadeOut(500);
    });
});
// Part 2
// Completion checkbox
//
// Include a checkbox with each todo item. 
// The checkbox should be checked when the item is completed
// And unchecked when the item is not completed

// Part 3
// Completed items only
//
// Update your REQUEST so that you are only fetching completed items
// Add a handler to the checkbox so that when a user checks the item
// It fades out the...