In this tutorial, we will create a shopping cart from scratch using JavaScript. We will be using the HTML5 and JavaScript APIs to create a simple shopping cart.
The first thing we need to do is create the HTML for our shopping cart. We will need a form to add items to our cart, and a table to display the items in our cart.
Item | Quantity |
---|---|
Item 1 | 1 |
Item 2 | 1 |
Now that we have our HTML in place, we can start writing our JavaScript code. We will need to create a function to add items to our cart, and a function to display the items in our cart.
function addItem(item, quantity) {
var tr = document.createElement(“tr”);
var td = document.createElement(“td”);
td.innerHTML = item;
td.setAttribute(“data-quantity”, quantity);
tr.appendChild(td);
var table = document.getElementById(“cart”);
table.appendChild(tr);
}
function displayCart() {
var table = document.getElementById(“cart”);
var tr = table.getElementsByTagName(“tr”);
var data = [];
for (var i = 0; i < tr.length; i++) { var td = tr[i].getElementsByTagName("td")[0]; data.push(td.innerHTML); } var html = ""; for (var i = 0; i < data.length; i++) { html += "
“;