3

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

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>

javascript代码

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

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

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

4

2 回答 2

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;
  }
});

( 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" />

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;
  }
}
于 2013-08-22T11:30:26.533 回答
0
<script type="text/javascript">
function atleast_onecheckbox()
        { 
         if (document.getElementById('invite').checked) {
            alert('the checkbox is checked');
            }
         else
           {
          alert("please check atleast one..");
          return false;
           }    
        }   
 </script>    
 <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" id="invite" value="">
      {{field}}
 </div>
 {% endfor %} 
 <input type="submit" class="btn btn-primary" value="Submit" onclick=" return  atleast_onecheckbox()"/>
</form>
于 2013-08-22T10:45:23.180 回答