0

I am trying to make an interactive button(to show a message in the console) with js, which just print a message in the console when the button is pressed. My js file is:

console.log("hello this is from cart.js")
var updateBtns = document.getElementsByClassName('update-cart')

for(var i=0; i<updateBtns.length; i++){
  updateBtns[i].addEventListener('click', function(){
    var productId = this.dataset.product
    var action = this.dataset.action
    console.log("inside loop")
    //console.log('product ID: ', productId, "Action: ", action)
  })
}

HTML:

<button data-product="{{ i.id }}" data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button>

Here inside loop message does not show anytime.... the consol just show the following message:

hello this is from cart.js
DevTools failed to load SourceMap: Could not load content for chrome-extension://ndjpnladcallmjemlbaebfadecfhkepb/editor/config.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME
DevTools failed to load SourceMap: Could not load content for chrome-extension://ndjpnladcallmjemlbaebfadecfhkepb/editor/content.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME

How can I solve this problem?

Kanchon Gharami
  • 777
  • 1
  • 11
  • 30

1 Answers1

1

It appears that your code works correctly when I add it to the snippet, but I think the issue might be related to how you load in your javascript code. If it is a <script> tag, could you make sure that it is included after the body tag?

So like this:

<html>
  <head>...</head>
  <body>
    ...
    <script src="your-javascript-file.js"></script>
  </body>
</html>

The issue could be that your script is being executed before the HTML elements are created.

console.log("hello this is from cart.js")

const dataset  = {
  product: [
    'product-1',
    'product-2',
    'product-3'
  ],
  action: (product) => { alert(product); }
}

const updateBtns = document.getElementsByClassName('update-cart')

for (let i = 0; i < updateBtns.length; i++) {
  updateBtns[i].addEventListener('click', function() {
    const productId = dataset.product[i]
    const action = () => {
      dataset.action(productId)
    };
    action();
    //console.log('product ID: ', productId, "Action: ", action)
  });
}
<button class="update-cart">1</button>
<button class="update-cart">2</button>
<button class="update-cart">3</button>
Titulum
  • 9,928
  • 11
  • 41
  • 79
  • Thanks a lot Titulum. Now its working perfectly!..... there was just a problem with – Kanchon Gharami Sep 17 '20 at 16:07