I am trying to get the count of selected items from an asp listbox using jquery but can't figure out how to do it. this is how I have it as of now, but I get "Cannot get property length of undefined or null reference" on selectedOptions property. var lb
fills with objectHtmlSelectElement,
so that seems right.
function CheckSelectionCount(sender, args) {
var lb = document.getElementById(sender.controltovalidate);
var count = lb.selectedOptions.length;
args.IsValid = count >= 1 && count <= 5;
}
Many similar questions remedy this using a selector combined with the :selected attribute, but I think I need to leverage the sender argument and store it in a variable.
I'm sure this will be easy for the experts on here! Thanks in advance
jQuery to get the count
function CheckSelectionCount(sender, args) {
var count = $("#" + sender.controltovalidate + " option:selected").length;
args.IsValid = count >= 1 && count <= 5;
}
Without jQuery
function CheckSelectionCount(sender, args) {
var lb = document.getElementById(sender.controltovalidate);
var opts = lb.options;
var count = 0;
for(var i=0; i<opts.length; i++) {
if(opts[i].selected) count++;
}
args.IsValid = count >= 1 && count <= 5;
}
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.