How to run JS function withou adding an event in HTML (f.e. onclick event)

Hi.
I’m trying to write a JS script that checks for checked checkboxes and adds a class “on” if checkbox is checked:

<body>
    <form action="index.html" method="post">
      <input type="checkbox" name="ve" value="ve1"><label for="ve">Vechicle1</label><br />
      <input type="checkbox" name="ve" value="ve2"><label for="ve">Vechicle2</label><br />
      <input type="checkbox" name="ve" value="ve3"><label for="ve">Vechicle3</label><br />
      <input type="checkbox" name="ve" value="ve4"><label for="ve">Vechicle4</label><br />
      <button type="button" name="button" onclick="checkOn()" value="Run function"></button>
    </form>
    <script type="text/javascript">
      function checkOn() {
        let boxes = document.forms[0];
        for (let i = 0; i < boxes.length; i++) {
          if (boxes[i].checked){
            boxes[i].className = "on";
          }
        }
      }
    </script>
  </body>

Im using onclick event on button to run my funcion, but how to run my function without adding events to html?

Just select the button with javascript using document.querySelector and hook up the addEventListener method that Javascript provides natively, just like this:

<script type="text/javascript">
      function checkOn() {
        let boxes = document.forms[0];
        for (let i = 0; i < boxes.length; i++) {
          if (boxes[i].checked){
            boxes[i].className = "on";
          }
        }
      }
     // Attach the event listener. (You should remove the reference from your HTML now)
     document.querySelector('button').addEventListener('click', checkOn);
</script>

Check out the docs at MDN: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

And all the valid events: https://developer.mozilla.org/en-US/docs/Web/Events

1 Like