Is this the best way to do this? Also feedback


#1

This is the project I am referring to: https://www.codecademy.com/courses/jquery-ext/projects/jquery-prj_listeasy

My initial "solve" for this project was this:

var template = function(text) {
  return '<p><input type="checkbox"><i class="glyphicon glyphicon-star"></i><span>' + text + '</span><i class="glyphicon glyphicon-remove"></i></p>';
};

var main = function() {
  $('form').submit(function() {
    var text = $("#todo").val();
    var html = template(text);
    
    //dont let add new blank object
    if (text === ""){
      return false;
    }  
    
    //add new
    else {   
    
    $(".list").append(html);
 	  $("#todo").val("");
    };
    
    return false;
  });
 
//star 
$(".glyphicon-star").on("click", function(){
  $(this).toggleClass("active");  
});
  
//remove
$(".glyphicon-remove").on("click", function(){
  $(this).parent().remove();  
});
  
};



$(document).ready(main);

Based on the project instructions, I initially thought I had completed the project. However, it has some issues because newly created elements are not possible to remove. I came up with the following way to overcome that:


var template = function(text) {
  return '<p><input type="checkbox"><i class="glyphicon glyphicon-star"></i><span>' + text + '</span><i class="glyphicon glyphicon-remove"></i></p>';
};

var addFunctionality = function(){
  //star
  $(".glyphicon-star").on("click", function(){
    $(this).toggleClass("active");  
  });
  
  //remove
  $(".glyphicon-remove").on("click", function(){
      $(this).parent().remove();  
  });
};

var main = function() {
  $('form').submit(function() {
    var text = $("#todo").val();
    var html = template(text);
    
    //dont let add new blank object
    if (text === ""){
      return false;
    }  
    
    //add new
    else {   
    
    $(".list").append(html);
 	  $("#todo").val("");
    };
    
    addFunctionality();
    
    return false;
  });
  
addFunctionality();  
  
};



$(document).ready(main);

My question is simply:

Is this the best way to overcome the issue, or is there a more efficient way?


#2

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.