从localStorage中删除选中的复选框

时间:2017-03-22 16:27:46

标签: javascript arrays checkbox checked

我的代码有点问题。我无法删除localstorage中的复选复选框,因为当我检查输入时,我无法从复选框中获取ID并比较两个数组。

1)我有产品ID id 2)我不知道如何才能识别只检查产品的输入

  var products = [];

    if (localStorage.getItem("products")) { // jezeli cos sie znajduje w products
    products = JSON.parse(localStorage.getItem("products")); // pobiera dane i przekazuje do funkcji
    drawTable(products);  // rysuje
  }

  function pushProduct() {
    var titleVal = document.getElementById('title').value;
    var amountVal = document.getElementById('amount').value;
    var priceVal = document.getElementById('price').value;

    products.push({ title: titleVal, amount: amountVal, price: priceVal});
    drawTable(products);
  }

  function drawTable(products) {
    var table = document.getElementsByTagName("tbody")[0];
    table.innerHTML = ''; // czysci za kazdym kliknieciem tablice

    products.forEach(function(product, index, products) {
        var tr = document.createElement("tr");

        var productTd = document.createElement("td");
        productTd.innerHTML = product.title; // umieszczam nazwe w td produktu

        var amountTd = document.createElement("td");
        amountTd.innerHTML = product.amount; // umieszczam ilosc w td odp za ilosc

        var priceTd = document.createElement("td");
        priceTd.innerHTML = product.price; // umieszczam cene w td ceny

        var sumTd = document.createElement("td");
        sumTd.innerHTML = product.price*product.amount; // umieszczam sume w td sumy


        var chbTd = document.createElement("td");

        var chb = document.createElement("input");
        chb.type = "checkbox";

        table.appendChild(tr);

        tr.appendChild(productTd);
        tr.appendChild(amountTd);
        tr.appendChild(priceTd);
        tr.appendChild(sumTd);
        tr.appendChild(chbTd);

        chbTd.appendChild(chb); // lewa to td, prawa to coś co wsadzam w to td

        var id = "id_" + index;
        console.log(id);

    });

    localStorage.setItem('products', JSON.stringify(products)); // zapis w local storage
  }
  function clearlocal(){

  localStorage.removeItem('products'); // czysci localstorage w products
//  localStorage.setItem('products', []); //  ustawienie localstorage na pusta tabele
// localStorage.clear(); - caly local
  location.reload();
  };
  function remove() {
        var checked = document.querySelectorAll("input[type='checkbox']:checked"); // :checked - stan ze zaznaczone
        checked.forEach(function(checkbox, index, array) { // foreach po tablicy checked
        //console.log(document.querySelectorAll("input[type='checkbox']"));
        checkbox.parentNode.parentNode.remove();  // usuwanie poszczegolnych tr  chb - > chbTd - > tr
    });
  }

0 个答案:

没有答案