-1

I have 2 separate files. A html and a js file. I get the following error:

(index):118 Uncaught TypeError: Cannot read property 'addEventListener' of null



Resources


html

<form><input id="product1" name="product1" type="checkbox" value="12" />
<input id="product1" name="product1" type="checkbox" value="13" />
<input id="product1" name="product1" type="checkbox" value="14" />
<button type="submit">Subscribe</button></form>

JS

const form = document.querySelector('form');

form.addEventListener('submit', e => {
  e.preventDefault();

  const values = Array.from(document.querySelectorAll('input[type=checkbox]:checked'))
    .map(item => item.value)
    .join(',');

  console.log(`test.com/addtocart?${values}`);
});
AA Shakil
  • 478
  • 4
  • 14
Kevin.a
  • 3,482
  • 4
  • 28
  • 65

1 Answers1

2

Thats because your HTML is not loaded when the JS is executing already. Include your javascript after your HTML and it will work (before </body>)

Xatenev
  • 6,240
  • 3
  • 15
  • 41