I have the following HTML form which can have many checkboxes. When the submit button is clicked, I want the user to get a javascript alert to check at least one checkbox if
$("#frmTest").submit(function(){
var checked = $("#frmText input:checked").length > 0;
if (!checked){
alert("Please check at least one checkbox");
return false;
}
});
$("#show").click(function() {
var count_checked = $("[name='chk[]']:checked").length; // count the checked rows
if(count_checked == 0)
{
alert("Please select any record to delete.");
return false;
}
if(count_checked == 1) {
alert("Record Selected:"+count_checked);
} else {
alert("Record Selected:"+count_checked);
}
});
$('#frmTest input:checked').length > 0
$('#fm_submit').submit(function(e){
e.preventDefault();
var ck_box = $('input[type="checkbox"]:checked').length;
// return in firefox or chrome console
// the number of checkbox checked
console.log(ck_box);
if(ck_box > 0){
alert(ck_box);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name = "frmTest[]" id="fm_submit">
<input type="checkbox" value="true" checked="true" >
<input type="checkbox" value="true" checked="true" >
<input type="checkbox" >
<input type="checkbox" >
<input type="submit" id="fm_submit" name="fm_submit" value="Submit">
</form>
<div class="container"></div>
if(jQuery('#frmTest input[type=checkbox]:checked').length) { … }
$('#frmTest').submit(function(){
if(!$('#frmTest input[type="checkbox"]').is(':checked')){
alert("Please check at least one.");
return false;
}
});
is(':checked') will return true if at least one or more of the checkboxes are checked.