-2

I want to disable submit button if no checkbox are checked in my form. However my function is not working and always allows the submit button to open the next page.

function test(){

var b = false;
var inputs = document.getElementsByTagName('input');

  for(var i = 0; i < inputs.length; i++) {

        if (inputs[i].checked == true){
        return true; 
   }  
 }

     return false;
}

Form

form name='checkBoxForm' action ='book.php' method='post' onsubmit='return test(this)

Checkbox - note javatest is another working function.

input type='checkbox' id =\"$id\" name='check_list[]' value=\"$seat\" onclick='javatest(this)
  • The issue is that you are `return`ing after encountering the first checked checkbox. Reverse your logic. Return false if you encounter one that is _unchecked_. Then, if you make it through the full loop, return true. – Patrick Q Dec 05 '19 at 18:37
  • Also, `(inputs[i].checked = true)` is an assignment, not an equality check. You want `==` there. Plus you're missing the `if` part. – Patrick Q Dec 05 '19 at 18:38

1 Answers1

-1

This is happening because you are not stopping the default action of a Submit button. You would need to use preventDefault() javascript function as the first line in your validation function to stop the default submit behavior. Below is an edited version of test:

function test(event){
event.preventDefault()
var b = false;
var inputs = document.getElementsByTagName('input');
....

Also, to submit the form (i.e. when you find at least 1 checked check-box), you would need to use form.submit event as below:

document.getElementByTagName("checkBoxForm").submit();

Hopefully, this should resolve the issue.

BusyCoder
  • 69
  • 5
  • It would be a great help to know why this received a -1. It should help me improve my future answers. – BusyCoder Dec 05 '19 at 19:11
  • 1
    It will probably help you to read [this](https://stackoverflow.com/questions/35037069/what-is-the-meaning-of-onsubmit-return-false-javascript-jquery/35037437) question and the related answer. It explains why the things you're saying need to be done do not. – Patrick Q Dec 05 '19 at 19:18