Holla Tech - Learn

To-Do List
 

Let’s create a To-Do list project using the concepts we have learned.
The To-Do list will be able to add new items to a list, as well as remove existing items.
First, we create the HTML: 

<h1>My To-Do List</h1>
<input type=“text” placeholder=“New item” />
<button id=“add”>Add</button>
<ol id=“mylist”></ol> 

 

NOTE!
Clicking the button should add the value of the input field to our <ol> list.
 


To-Do List
 

Now, having the HTML ready, we can start writing our jQuery code.
First, we handle the click event for the button:

$(function() {
  $(“#add”).on(“click”, function() {
    //event handler
  });
}); 

 

Inside the event handler we select the value of the input field and create a new <li> element, adding it to the list:

var val = $(“input”).val();
if(val !== ) {
  var elem = $(“<li></li>”).text(val);
  $(elem).append(“<button class=’rem’>X</button>”);
  $(“#mylist”).append(elem);
  $(“input”).val(“”); //clear the input

 

The code above takes the value of the input field, assigns it to the val variable. The if statement checks that the value is not blank and then creates a new <li> element. A button for removing it is added, after which the newly created element is added to the <ol id=”mylist”> list.

Here’s the complete code in action:

$(function() {
  $(“#add”).on(“click”, function() {
    var val = $(“input”).val();
    if(val !== ) {
      var elem = $(“<li></li>”).text(val);
      $(elem).append(“<button class=’rem’>X</button>”);
      $(“#mylist”).append(elem);
      $(“input”).val(“”);
    }
  });
}); 

 

NOTE!
The remove button is not working yet. We will handle it in the next section!

To-Do List
 

All that is left to do is handle the click event on the class=”rem” button and remove the corresponding <li> element from the list.

$(“.rem”).on(“click”, function() {
  $(this).parent().remove();
}); 

 

Remember, this is the current object. The code above removes the parent of the current object, which in our case is the parent of the remove button, the <li> element.

The complete code:

$(function() {
  $(“#add”).on(“click”, function() {
    var val = $(“input”).val();
    if(val !== ) {
     var elem = $(“<li></li>”).text(val);
     $(elem).append(“<button class=’rem’>X</button>”);
     $(“#mylist”).append(elem);
     $(“input”).val(“”);
     $(“.rem”).on(“click”, function() {
      $(this).parent().remove();
     });
    }
  });
}); 

 

NOTE!
The To-Do List was just a short demonstration of how to handle events and build a simple project.

BACK NEXT

CLICK ON THE BUTTON BELOW TO GO TO THE jQUERY MAIN COURSE PAGE. 

jQUERY MAIN COURSE PAGE

 


© License: All Rights Reserved 


CONTACT HOLLA TECH – LEARN SUPPORT