0

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

Community
  • 1
  • 1
wizloc
  • 2,202
  • 4
  • 28
  • 54
  • I see no jQuery there. The error means `selectedOptions` is undefined. Where do you set it? – epascarello Oct 15 '15 at 16:04
  • Now that you changed it, there is no selectedOptions in JavaScript for a select. Hence undefined. – epascarello Oct 15 '15 at 16:09
  • http://stackoverflow.com/questions/5866169/getting-all-selected-values-of-a-multiple-select-box-when-clicking-on-a-button-u – epascarello Oct 15 '15 at 16:12
  • Sorry, that got left out. I dont understand the downvote, this is a valid question. I got the selectedOptions property by viewing another question on SO. Maybe the question should be reworded to what should I use instead? – wizloc Oct 15 '15 at 16:12
  • Well that is not a valid property so it is wrong. You need to look at the link I posted to count the options that were selected. If you are actually using jQuery it is easy. – epascarello Oct 15 '15 at 16:15
  • After testing it seems selectedOptions works in chrome but not IE. I can use jquery, this isnt javascript exclusive. Just because its plain JS now doesnt mean i cant remedy it with JQuery – wizloc Oct 15 '15 at 16:17

1 Answers1

1

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;
}
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • That worked. Sorry if my wording was confusing, I often don't know how best to word to depict the problem. – wizloc Oct 15 '15 at 16:24