STDIO Training

45 bundles
1 file2 months ago
3

HTML + Js Practice - Cart

Giỏ hàng với HTML và JavaScript. Thực hành Js + HTML.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485<html>
  <head>
    <script>
      function removeFromCart(id) {
        let model = document.getElementById("cartModel");
        let products = model.value.trim() === "" ? [] : JSON.parse(model.value);

        let foundIndex = -1;
        for (let i = 0; i < products.length; i++) {
          if (products[i].id === id) {
            foundIndex = i;
            break;
          }
        }

        if (foundIndex !== -1) {
          products.splice(foundIndex, 1);

          model.value = JSON.stringify(products);

          let view = document.getElementById("cartView");
          let viewHtml = `<p>${products.length} sản phẩm trong giỏ hàng.</p>`;

          for (let i = 0; i < products.length; i++) {
            viewHtml += `<li id="${products[i].id}" onclick="removeFromCart('${products[i].id}')">${products[i].name}</li>`;
          }

          view.innerHTML = viewHtml;
        }
      }

      function addToCart(name, id) {
        let model = document.getElementById("cartModel");
        let products = model.value.trim() === "" ? [] : JSON.parse(model.value);

        let foundIndex = -1;
        for (let i = 0; i < products.length; i++) {
          if (products[i].id === id) {
            foundIndex = i;
            break;
          }
        }

        if (foundIndex === -1) products.push({ name, id });

        model.value = JSON.stringify(products);

        let view = document.getElementById("cartView");
        let viewHtml = `<p>${products.length} sản phẩm trong giỏ hàng.</p>`;

        for (let i = 0; i < products.length; i++) {
          viewHtml += `<li id="${products[i].id}" onclick="removeFromCart('${products[i].id}')">${products[i].name}</li>`;
        }

        view.innerHTML = viewHtml;
      }
    </script>
  </head>
  <body>
    <ul>
      <li>
        Móc khóa InterNOT
        <button onclick="addToCart('Móc khóa InterNOT', 'moc-khoa-internot')">
          Cho vào giỏ
        </button>
      </li>
      <li>
        Móc khóa PTS
        <button onclick="addToCart('Móc khóa PTS', 'moc-khoa-pts')">
          Cho vào giỏ
        </button>
      </li>
      <li>
        Móc khóa Ai
        <button onclick="addToCart('Móc khóa Ai', 'moc-khoa-ai')">
          Cho vào giỏ
        </button>
      </li>
    </ul>

    <input type="hidden" id="cartModel" />
    <h3>Giỏ hàng</h3>
    <div id="cartView"></div>
  </body>
</html>