简体   繁体   中英

JavaScript Max number of checked input type checkbox

Using ASP.NET to generate several checkboxes. Looking for a JavaScript solution that will test any checkbox starting with the name pdf* to see if more than 5 are checked, then alert over that number.

There are other checkboxes I do not want this to run on that do not have the name pdf* .

Thanks in advance.

here is an example of my checkboxs:

<td><input type="checkbox" name="pdf14" value="2250"></td>

<td><input type="checkbox" name="pdf15" value="2251"></td>

<td><input type="checkbox" name="pdf16" value="2252"></td>
 
<td><input type="checkbox" name="print" value="2253"></td> 

<<<NOT A PART OF THE COUNT

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();        
        }
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM