-1

I'm getting a error on the console when executing this code. Basically I want to send a console log when clicking on a button.

var send = document.getElementById("sendButton");

send.addEventListener("click", function () {
  console.log("text");
});
<button id="sendButton">Submit</button>

How can I resolve this?

halfer
  • 19,824
  • 17
  • 99
  • 186
bilalk
  • 19
  • 5
  • 1
    As a rule of thumb, most of the time if you are thinking about binding a click event handler to a submit button then you should be binding a submit event handler to a form. – Quentin Sep 07 '22 at 12:01
  • 1
    add you function inside this `document.addEventListener('DOMContentLoaded', function() {var send = document.getElementById("sendButton"); send.addEventListener("click", function () { console.log("text"); });}, false);` – uditkumar01 Sep 07 '22 at 12:02
  • 1
    Just adding to what @Quentin said, Use `event.preventDefault();` to prevent the default action of submit button i.e. submitting the form. – Rayon Sep 07 '22 at 12:03
  • @uditkumar01 Thank you so much, this piece of code worked. I don't get what's the difference? On my visual studio code my code doesn't work but on this website it does. Could you please explain that? – bilalk Sep 07 '22 at 12:50
  • @bilalk you need to make sure you script should run when your whole webpage is loaded properly, `DOMContentLoaded` event is doing that for us, you can read more about this here https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event – uditkumar01 Sep 08 '22 at 00:27

1 Answers1

-1

Your code is fine, should work. Must be something else.

BTW you can use inline onclick if you prefer : [https://www.freecodecamp.org/news/html-button-onclick-javascript-click-event-tutorial/][1]

Simon Prato
  • 23
  • 1
  • 3