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

6
  • I see no jQuery there. The error means selectedOptions is undefined. Where do you set it? Commented Oct 15, 2015 at 16:04
  • Now that you changed it, there is no selectedOptions in JavaScript for a select. Hence undefined. Commented Oct 15, 2015 at 16:09
  • stackoverflow.com/questions/5866169/… Commented Oct 15, 2015 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? Commented Oct 15, 2015 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. Commented Oct 15, 2015 at 16:15

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

That worked. Sorry if my wording was confusing, I often don't know how best to word to depict the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.