2013-08-22 64 views
2

我有一个包含复选框字段的形式,现在在表单提交,我们应该检查ATLEAST一个复选框是否被选中检查ATLEAST一个复选框表单提交检查

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>  

所以,当我点击了提交butto n,表单重定向到action中提到的网址,但它甚至没有触发javascript功能atleast_onecheckbox()

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

+1

'onsubmit'应该是形式,而不是提交按钮。你也必须'返回false'或'event.preventDefault()'来防止表单提交。 – Passerby

回答

3

您不应该直接在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应该是:

  • 连接到形式
  • 应防止的默认事件提交
  • 返回false

因此它涵盖了一切。喜欢这里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; 
    } 
} 
+0

谢谢它的工作! –

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> 
+0

仍然一样,重定向不显示更改消息 –

+0

我编辑了答案。可以请你尝试一下... – shemy

+0

是的,它的工作方式是这样的,但是我们不能使用相同的ID作为所有复选框的权利?,这应该是明显的,因为我已经基于复选框字段实施了ckeckall/unckeckall functionlaity –