Creating a Shopping Cart using only HTML/JavaScript

6

I'm not sure what to do in order to complete this project. I need to create a shopping cart that uses only one HTML page. I have the table set up showing what is being sold but where I am lost is the JavaScript.

I don't know how to link the "Add to Cart" button with all the necessary data( The name, description, and price) to be able to add it to the cart. I don't need to be able to remove it from the cart, but it does need to show the total. After searching online for a few answers, I've tried some things but just cannot figure it out.

Any help is definitely appreciated because I am completely lost at this point and am new to JavaScript in general.

This is the jsFiddle but that was a little confusing to me, because it's working differently on there than if I just went to Run in Notepad++

jsFiddle: http://jsfiddle.net/renavi/ATjvt/5/

function AddtoCart() {
  console.log('hi');
  var x = document.getElementById('Items');
  var new_row = x.rows[1].cloneNode(true);
  var len = x.rows.length;
  new_row.cells[0].innerHTML = len;
  var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
  inp1.id += len;
  inp1.value = '';
  var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
  inp2.id += len;
  inp2.value = '';
  x.appendChild(new_row);
}

The direct file is here

Pastebin: http://pastebin.com/sutGWjSY

This question is tagged with javascript html arrays html-table cart

~ Asked on 2013-04-30 06:54:27

The Best Answer is


9

You simply need to use simpleCart

It is a free and open-source javascript shopping cart that easily integrates with your current website.

You will get the full source code at github

~ Answered on 2013-04-30 06:58:39


3

For a project this size, you should stop writing pure JavaScript and turn to some of the libraries available. I'd recommend jQuery (http://jquery.com/), which allows you to select elements by css-selectors, which I recon should speed up your development quite a bit.

Example of your code then becomes;

function AddtoCart() {
  var len = $("#Items tr").length, $row, $inp1, $inp2, $cells;

  $row = $("#Items td:first").clone(true);
  $cells = $row.find("td");

  $cells.get(0).html( len );

  $inp1 = $cells.get(1).find("input:first");
  $inp1.attr("id", $inp1.attr("id") + len).val("");

  $inp2 = $cells.get(2).find("input:first");
  $inp2.attr("id", $inp2.attr("id") + len).val("");

  $("#Items").append($row);
    }

I can see that you might not understand that code yet, but take a look at jQuery, it's easy to learn and will make this development way faster.

I would use the libraries already created specifically for js shopping carts if I were you though.

To your problem; If i look at your jsFiddle, it doesn't even seem like you have defined a table with the id Items? Maybe that's why it doesn't work?

~ Answered on 2013-04-30 07:13:26


Most Viewed Questions: