patternjavascriptMinor
Check whether all checkboxes are checked and then execute a function
Viewed 0 times
checkboxesareallandfunctionthencheckedcheckwhetherexecute
Problem
How could I make this code dry?
$("#btnSubmitToCheckOut").click(function(event) {
var isSelected = [];
$(".age_agree :checkbox").each(function() {
if ($(this).is(":checked")) {
isSelected.push("true");
} else {
isSelected.push("false");
}
});
if ($.inArray("false", isSelected) < 0) {
$(this).parents('form').submit();
} else {
alert('Please accept all the Terms and Conditions');
}
});Solution
I was thinking something along these lines. The condition checks whether there are no unchecked checkboxes (length of the selection is
0) and then executes the appropriate branch.$("#btnSubmitToCheckOut").click(function(event) {
if ($('.age_agree input[type="checkbox"]').not(':checked').length == 0) {
$(this).parents('form').submit();
} else {
alert('Please accept all the Terms and Conditions');
}
});Code Snippets
$("#btnSubmitToCheckOut").click(function(event) {
if ($('.age_agree input[type="checkbox"]').not(':checked').length == 0) {
$(this).parents('form').submit();
} else {
alert('Please accept all the Terms and Conditions');
}
});Context
StackExchange Code Review Q#70392, answer score: 5
Revisions (0)
No revisions yet.