2
http://jsfiddle.net/bald1/Su97P/2/

I dont know whats wrong with this code. I would like to click on the green div and by that click add "data-productName" to the "cart".

   var cart = []; 
var cartElement = document.getElementById("cart");



function addToCart(productName) {
   cart.push(productName); 
   cartElement.innerHTML = cart.join("<br>");  
}


var someDiv = document.getElementById("product");

someDiv.addEventListener("click", function() {
   var str = someDiv.dataset.productName; 

   addToCart(str); 

}, false);

1 Answer 1

3

Change it to productname, since the data attributes are lowercased in your case (camelcased in case of any more hyphens after the first one) and added to the dataset, you need to access it as productname instead of productName.

someDiv.addEventListener("click", function() {
   var str = someDiv.dataset.productname; 
   addToCart(str); 
}, false);

productName will work had your attribute been data-product-name.

See the documentation regarding the rules.

  • any dash (U+002D) is removed;
  • any letter following a dash (U+002D), before its removal, is set in its uppercase counterpart.
Sign up to request clarification or add additional context in comments.

9 Comments

Im sorry, change which part to productname?
@user2915962 see the casing... when you do someDiv.dataset.productname
I think i found it, took care of some old ones to =)
@user2915962 you can without duplicating the ids. provide them all a classname as product and use document.getElementsByClassName('product'), loop though them attach the handler and then inthe handler use this.dataset.productname
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.