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


#1

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?
#2

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

Also, form.operation[] is invalid syntax.


#3

actually operation is my name for checkbox field

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

#4

You can do it like this:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Checkbox validation</title>
</head>
<body>
<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">
</form>

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

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

#5

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 ?


#6

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

On the server.


#7

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?


#8

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.