jqueryhtml-selecthidden-field

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.


Solution

  • 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);