简体   繁体   English

如果条件失败,则取消表单提交

[英]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.复选框 - 注意 javatest 是另一个工作功能。

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.您需要使用 preventDefault() javascript 函数作为验证函数中的第一行来停止默认提交行为。 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:此外,要提交表单(即当您找到至少 1 个选中的复选框时),您需要使用 form.submit 事件,如下所示:

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

Hopefully, this should resolve the issue.希望这应该可以解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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