var inputs = document.getElementsByTagName("input");
var numSelected = 0;
var current;
for (var i=inputs.length;i--;) {
current = inputs[i];
if (current.type.toLowerCase() == "checkbox" && current.checked && current.name.indexOf("pdf") == 0) {
current++;
};
};
if (current > 5) {
alert("You've got " + current + " selected! :(");
}
If you happened to use jQuery, it'd be as easy as
var selectedPdfCheckboxes = $('input:checkbox[name^=pdf]');
if (selectedPdfCheckboxes.length > 5) {
alert("You've got " + selectedPdfCheckboxes.length + " selected! :(");
}
Edit:
The jQuery selector I've used (^=
) reads as "start with", so no * equivalent is needed.
The jQuery code will execute wherever it is placed, however it must be executed no sooner than document.ready()
, to ensure the elements you are selecting are present in the DOM. If you place it inside document.ready, it will fire as soon the document ready event is fired. You might want to place the code inside an event handler for another event.. such as the submission of a form?
$(document).ready(function () {
$("#aForm").bind('submit', function (e) {
var selectedPdfCheckboxes = $('input:checkbox[name^=pdf]');
if (selectedPdfCheckboxes.length > 5) {
alert("You've got " + selectedPdfCheckboxes.length + " selected! :(");
e.preventDefault();
}
});
});