提交表单时至少选中一个复选框

Shi*_*dla 3 javascript forms django checkbox submit

我有一个包含复选框字段的表单,现在在提交表单时,我们应该检查是否至少选中了一个复选框

HTML代码

<form id="form_check" class="form" action="/path/to/some/url" method="POST">
  {% for field in fields %}
     <div class="check_fields">  
         <input class="select-unselect" type="checkbox" name="invite" value="">
          {{field}}
     </div>
  {% endfor %} 
     <input type="submit" class="btn btn-primary" value="Submit" onsubmit="atleast_onecheckbox()"/>
</form>
Run Code Online (Sandbox Code Playgroud)

JavaScript代码

<script type="text/javascript">
    function atleast_onecheckbox()
            {
             var value = $("[name=invite]:checked").length > 0);
                 alert(value) ;      
                 if (!value)
                      {
                    alert("Please.....");
                       }
            }   
</script>    
Run Code Online (Sandbox Code Playgroud)

因此,当我单击“提交”按钮时,表单将重定向到中提到的url action,但它甚至没有命中javascript函数atleast_onecheckbox()

上面的代码有什么问题,任何人都可以使上面的代码工作吗?

die*_*ump 5

您不应该在HTML中直接附加JavaScript事件,这是一个非常糟糕的做法。相反,因为使用jQuery,所以应该使用jQuery事件处理程序:

$('#form_check').on('submit', function (e) {
  if ($("input[type=checkbox]:checked").length === 0) {
      e.preventDefault();
      alert('no way you submit it without checking a box');
      return false;
  }
});
Run Code Online (Sandbox Code Playgroud)

http://jsbin.com/IXeK/1/edit

如果您真的想使用HTML onsubmit,即使它很糟糕(并且您应该只是想一下而感到难过),onsubmit也应该是:

  • 附在表格上
  • 应该阻止默认事件提交
  • 返回假

因此,它涵盖了所有内容。像这里http://jsbin.com/IXeK/2/edit

<form onsubmit="return atleast_onecheckbox(event)" id="form_check" class="form" action="/path/to/some/url" method="POST">
 <div class="check_fields">  
     <input class="select-unselect" type="checkbox" name="invite" value="">
 </div>
 <input type="submit" class="btn btn-primary" value="Submit" />
Run Code Online (Sandbox Code Playgroud)

function atleast_onecheckbox(e) {
  if ($("input[type=checkbox]:checked").length === 0) {
      e.preventDefault();
      alert('no way you submit it without checking a box');
      return false;
  }
}
Run Code Online (Sandbox Code Playgroud)