Reputation: 117
Although the following function has a little problem. But I can not find. Every time either checkbox is checked or not but form was not submitted!!
<input type="checkbox" name="chk_user[]" value="1" class="chk_delete" id="1" />
<input type="checkbox" name="chk_user[]" value="2" class="chk_delete" id="2" />
<input type="checkbox" name="chk_user[]" value="3" class="chk_delete" id="3" />
<input type="checkbox" name="chk_user[]" value="4" class="chk_delete" id="4" />
<script>
$("form").submit(function() {
$('.chk_delete').each(function(){
if($(this).is(':checked')){
return true;
}
});
alert("No entry was selected!");
return false;
});
</script>
Can anybody locate the problem?
The following is working, but I don't understand why. Any good logic?
$("form").submit(function(e) {
if(!$('input[type=checkbox]:checked').length) {
e.preventDefault();
alert("No entry was selected!"); }
return true; });
Upvotes: 0
Views: 107
Reputation: 33870
You are using the return true
into the each
loop. Using return in the each loop just mean if the loop continue (on true
) or if it stop (on false
).
That beign said, you script will alway roll hover a return false
, preventing the form from submiting.
What you could do
If you want to keep the loop, save if it's true or false in a var!
var isChecked = false;
$('.chk_delete').each(function(){
isChecked = $(this).is(':checked')
return !isChecked;
});
return isChecked;
OR
Use your working script, I don't see what's wrong with it
$("form").submit(function(e) {
if(!$('input[type=checkbox]:checked').length) {
e.preventDefault();
alert("No entry was selected!");
}
return true;
});
$('input[type=checkbox]:checked')
select every checked box. So $('input[type=checkbox]:checked').length
take the length. Having !
is the same thing as !=
.
Finally, !$('input[type=checkbox]:checked').length
is a shotcut for $('input[type=checkbox]:checked') != 0
. If true, it .preventDefault()
wich prevent the form of submiting.
Upvotes: 0
Reputation: 74217
Give this a whirl:
$("form").submit(function(e) {
if(!$('input[type=checkbox]:checked').length) {
e.preventDefault();
alert("No entry was selected!"); }
return true; });
Upvotes: 1