vendredi 18 janvier 2019

populate value of array an boolean value to checkbox

I have started to learn js and I am trying to take a boolean value in a array and populate it to checkboxes.

This is the HTML portion:

<label style="font: bold 1.5em courier !important">
 <input type="checkbox" id="filterTodo" onclick="validate()">Hide completed
 </label>

This is my array:

let todos = [{
  text: 'Order airline tickets',
  completed: false
},{
  text: 'Vaccine appointment',
  completed: true
}, {
  text: 'Order Visa',
  completed: true
}, {
  text: 'Book hotell',
  completed: false
}, {
  text: 'Book taxi to airport',
  completed: true
}]

And I set a global variabel set to false:

let filterTodos = false

If that value is unchecked as its default is, it should show the whole array, if checked it should only show the the items in the array that have the value of completed:true

So my first task to actually show all the items in the array, I do get to show all the text values of each item, and a checkbox, but I am getting value undefined on the checkboxes and labels.

This is the code for that shows the array:

function addTodo(add_todo) {
  const p = document.createElement('p')
    p.textContent = add_todo.text
    document.querySelector('body').appendChild(p)

    let checkBox = document.createElement("input")
    let label = document.createElement("label")
        checkBox.type = "checkbox"
        checkBox.value = addTodo.completed
        document.querySelector('body').appendChild(checkBox)
        document.querySelector('body').appendChild(label)
        label.appendChild(document.createTextNode(todos.completed))

}

function showTodos(show_todos) {
  //function to show the whole object
  show_todos.forEach(function (todo) {
    addTodo(todo);  
  }) 
}

showTodos(todos);

I think there should be some if clause in my showTodos function where, if the checkbox with id filterTodo is checked, then it should loop through the array and only show the items where the completed value is true.

I sort of tried to play around with following code, but just testing with console.log i am getting only false values regardless if the checkbox is checked or not. This is that portion of the code:

function validate() {
    let isChecked = false;
    if (document.getElementById(('filterTodo').checked)) {
      isChecked = true;
      console.log(isChecked);
    } else {
      isChecked = false;
      console.log(isChecked);
    }
  }

So, the main issue is, I am not able to show the proper value for the checkboxes if the are completed or not, they are all undefined.

The other problem is, I am not able to write the code if I check checkbox to filter the array and only show either all tasks or only the ones that are completed




Aucun commentaire:

Enregistrer un commentaire