Whats wrong with this JavaScript code to validate the checkbox field?


this is what I did , but can’t figure out why its not showing alert message

      function checkForm()
if(!form.operation[].checked) {
  alert("Please slelect at least one operation");
  return false;
return true;

this is my submit button

<input type="button" name="submit" value="GENERATE" id="gen"  onclick="return checkForm();">

where I went wrong?

How to add the validation to these checkboxes? Where I am going wrong?

In the code you supplied, form is not defined anywhere.

Also, form.operation[] is invalid syntax.


actually operation is my name for checkbox field

                    <input type="checkbox" name="operation[]" value="Addition" checked>
                </label><span class="checkmark"></span><br>


You can do it like this:

<!DOCTYPE html>
<html lang="en">
  <meta charset="UTF-8">
  <title>Checkbox validation</title>
<form action="submit.php">
  <input type="checkbox" name="operation[]" value="Addition">Addition<br>
  <input type="checkbox" name="operation[]" value="Subtraction">Subtraction<br>

  <input type="submit" value="Submit">

    const form = document.querySelector("form");
    const checkboxes = document.querySelectorAll('input[type="checkbox"]');

    form.addEventListener("submit", (e) => {
      if(![...checkboxes].some(x => x.checked)) {
        alert("Please select at least one option");


hey thanks its working now but why my output is not running after adding this ? Do you have any idea ? because I did nothing but just add the above code in my script.js file and then tried to run but its not showing me output.
Is there any other way to validate the checkbox instead of js ?


No idea. You’d have to provide more code.

On the server.


when I removed that code then its start working and when I add that code it doesn’t , I think its happening because I am using eval() function ,
am I right?


No idea without seeing your code. Sorry.

Plus, you probably shouldn’t be using eval().

closed #9

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.