Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of options in a list

I'm trying to count the number of options in a list. However, some of the options have been hidden due to the search text entered into an input box.

I started off looking into .size() and .length but was only getting the full list rather than those that were not hidden. In order to simplify, I've changed it to try and find the hidden options (I can use :not later).

$('#txtListSearch').keyup(function(evt) {
    if($(this).val().length < 1) {
        $('#selContactLists option').show();
    } else {
        $('#selContactLists option:not(:contains("' + $(this).val() + '"))').hide();

        if($('#selContactLists').size()) {
            $('#selContactLists option:contains("' + $(this).val() + '")').first().attr('selected', 'selected');                
        } else {
        }
    }
    console.log($('#selContactLists option').filter(':hidden'));
});

I've also tried: console.log($('#selContactLists option:hidden')); I never quite get the number I'm expecting. Can anyone see where I'm going wrong?

Even more odd, is that if I change the "size" of the select so that more than one item is shown by default, on chrome it never hides any of the options.

like image 722
David Avatar asked Aug 14 '12 14:08

David


2 Answers

This works for me, but you might want to manually add and remove the css display:none from the elements, instead of using show/hide, for compatibility reasons...

alert($('#selContactLists option:not([style*=none])').length);
like image 190
LJ2 Avatar answered Sep 29 '22 14:09

LJ2


Use jQuery's :visible selector.

$('#selContactLists option:visible').length;
like image 37
James Hill Avatar answered Sep 29 '22 14:09

James Hill