开发者

JavaScript Max number of checked input type checkbox

开发者 https://www.devze.com 2023-01-07 22:14 出处:网络
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.

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

精彩评论

暂无评论...
验证码 换一张
取 消