todo.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. // to do list
  2. var todos = [{
  3. text: "take out the trash",
  4. done: false,
  5. id: 0
  6. }];
  7. var currentTodo = {
  8. text: "",
  9. done: false,
  10. id: 0
  11. }
  12. document.getElementById("todo-input").oninput = function (e) {
  13. currentTodo.text = e.target.value;
  14. };
  15. /*
  16. //jQuery Version
  17. $('#todo-input').on('input',function(e){
  18. currentTodo.text = e.target.value;
  19. });
  20. */
  21. function DrawTodo(todo) {
  22. var newTodoHTML = `
  23. <div class="pb-3 todo-item" todo-id="${todo.id}">
  24. <div class="input-group">
  25. <div class="input-group-text">
  26. <input type="checkbox" onchange="TodoChecked(${todo.id})" aria-label="Checkbox for following text input" ${todo.done&& "checked"}>
  27. </div>
  28. <input type="text" readonly class="form-control ${todo.done&&" todo-done "} " aria-label="Text input with checkbox" value="${todo.text}">
  29. <button todo-id="${todo.id}" class="btn btn-outline-secondary bg-danger text-white" type="button" onclick="DeleteTodo(this);" id="button-addon2 ">X</button>
  30. </div>
  31. </div>
  32. `;
  33. var dummy = document.createElement("DIV");
  34. dummy.innerHTML = newTodoHTML;
  35. document.getElementById("todo-container").appendChild(dummy.children[0]);
  36. /*
  37. //jQuery version
  38. var newTodo = $.parseHTML(newTodoHTML);
  39. $("#todo-container").append(newTodo);
  40. */
  41. }
  42. function RenderAllTodos() {
  43. var container = document.getElementById("todo-container");
  44. while (container.firstChild) {
  45. container.removeChild(container.firstChild);
  46. }
  47. /*
  48. //jQuery version
  49. $("todo-container").empty();
  50. */
  51. for (var i = 0; i < todos.length; i++) {
  52. DrawTodo(todos[i]);
  53. }
  54. }
  55. RenderAllTodos();
  56. function DeleteTodo(button) {
  57. var deleteID = parseInt(button.getAttribute("todo-id"));
  58. /*
  59. //jQuery version
  60. var deleteID = parseInt($(button).attr("todo-id"));
  61. */
  62. for (let i = 0; i < todos.length; i++) {
  63. if (todos[i].id === deleteID) {
  64. todos.splice(i, 1);
  65. RenderAllTodos();
  66. break;
  67. }
  68. }
  69. }
  70. function TodoChecked(id) {
  71. todos[id].done = !todos[id].done;
  72. RenderAllTodos();
  73. }
  74. function CreateTodo() {
  75. newtodo = {
  76. text: currentTodo.text,
  77. done: false,
  78. id: todos.length
  79. }
  80. todos.push(newtodo);
  81. RenderAllTodos();
  82. }