mercredi 3 août 2016

Set an ID for each checkbox item dynamically in pure javascript (No JQuery)

I have an object array called storedItems with 2 objects cbitem(value of checkbox) and isChecked (true/false).

I am trying to do 2 things now:

Task1: Read the value of storedItems.cbItem and construct the checkbox using DOM.
Task2: Read the value of storedItems.isChecked and check the appropriate checkboxes.

I have already accomplished task1. need help with task2.

// sample code:

var storedItems = JSON.parse(localStorage.getItem("allItems"));
    for(var i=0;i<storedItems.length;i++)
    {
        createCheckBox(storedItems[i].cbItem);
        if(storedItems[i].isChecked)
         {
           document.getElementByID(' ').checked=true;
        //Here I need to check the appropriate checkbox. But I don't have an
         // ID for my  checkbox. How do I access the item without the ID ? 
         //If not possible, how do I dynamically set an ID for each item.   


         }

// Code for creating Checkbox

function createCheckBox(todoItem){  
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "name";
checkbox.value=todoItem;

var label = document.createElement('label')
label.htmlFor = "name";
label.appendChild(document.createTextNode(todoItem));
}




Aucun commentaire:

Enregistrer un commentaire