Question

I'm designing a sample shopping website, and one of the things I want it to be able to do is display the number of items in the shopping cart. I figure the way to do this is to code it so that each time a "purchase" button is clicked to add +1 to the variable displayed in the cart text. The code I have so far is

function cart() {
  var cart = document.getElementById("cart").value;
  var cart = cart + 1;
  document.GetElementById("cart").innerHTML=cart
}

and the button code is

<input type="button" value="Purchase" onclick="cart()" />

the display code is

  <p id="cart"> 0 </p>
Was it helpful?

Solution

Your call to document.GetElementById() should follow case-sensitive naming conventions and therefore be called:

document.getElementById()

You can try this, which includes some safety typecasting:

function cart() {
    var itemCount = document.getElementById("cart").innerHTML;
    document.getElementById("cart").innerHTML = Number(itemCount) + 1;
}

Check this fiddle for a demonstration

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top