检查atleast一个复选框在表单提交上检查 [英] check atleast one checkbox is checked on form submission
问题描述
我有一个由复选框字段组成的表单,现在在表单提交时我们应该检查是否至少选中一个复选框
I have a form that consists of checkbox fields, now on form submission we should check whether atleast one checkbox is checked
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>
所以当我点击提交按钮时,表单将重定向到 action
,但它甚至不会触发javascript函数 atleast_onecheckbox()
So when i clicked on the submit button, the form is redirecting to the url mentioned in the action
, but its not even hitting the javascript function atleast_onecheckbox()
上面的代码有什么问题,任何人都可以使上面的代码工作吗?
what wrong in the above code, can anyone please make the above code work ?
推荐答案
你不应该附加JavaScript事件直接在HTML中,这是一个非常糟糕的做法。
相反,因为你使用jQuery,你应该使用jQuery事件处理程序:
You shouldn't attach JavaScript event directly in the HTML, this is a really bad practice. Instead, because you use jQuery, you should use jQuery event handler :
$('#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,即使是坏的(你应该觉得不好意思),这个提交应该是:
If you really want to use HTML onsubmit, even if it's bad (and you should feel bad just by thinking of it), the onsubmit should be:
- 附加到表单
- 应该阻止提交的默认事件
- return false
所以它涵盖了一切。像这里 http://jsbin.com/IXeK/2/edit
So it covers everything. Like here 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;
}
}
这篇关于检查atleast一个复选框在表单提交上检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!