简体   繁体   中英

Cancel form submission if criteria fails

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)

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 (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM