Exercise - jQuery AJAX

Todo handling

by Satish Kesiboyana

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>
    
    
</div>

CSS

ul{
    list-style:none;
    padding:0;
    margin:0;
}

li {
 padding:0;
    margin:0;
}

#modal{
    display:none;
    position:absolute;
    top:50%;
    left:50%;
    width:50%;
    height:50%;
    background-color:#f90;
    color:#fff;
}

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

var prom = $.getJSON('http://jsonplaceholder.typicode.com/todos?userId=5');

// display a loading thingy...

prom.done(function(response) {
  // console.log(response);
    
    // hide loading thingy...
    
    var $containerEl = $(".container");
    var $newUl = $("<ul></ul>");
    
    for (var i=0; i<response.length; i++) {
     
        var $newLi = $("<li><input type='checkbox' value='1' /></li>");
        
        if (response[i].completed) {
            
            $newLi.find("input").attr("checked", "true");
            
        }
        
        $newLi.attr("data-id", response[i].id);
        
        $newLi.append(" " + response[i].title);
        
        $newUl.append($newLi);
        
    }
    
    $containerEl.append($newUl);
    
});

prom.always(function() {
   
    // hide my loading thingy...
    
});

prom.fail(function(){
   
    // display or render a small element in the page
    // that indicates an error to the user
    
});

function displayUser() {
 
    var $containerEl = $(".container");
    
    var $modal = $("<div id='modal'></div>");
    
    $modal.hide();
    
    $modal.html("User is...");
    
    $containerEl.append($modal);
    $modal.fadeIn();
    
}

// 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

$(".container").on("change", "input[type='checkbox']", function(e) {
   
   ...