Martin Zhai Martin Zhai - 9 months ago 19
Javascript Question

How to get visible options' count of HTML select tag, with multiple attribute set, while size not set?

In my case, I want to get the select element's visible options' count (By visible options' count, I mean how many options are visible without scrolling. Thanks Matthew). If size attribute is set, then element.size is the value I need. When it isn't, things get a little tricky.

For example, in following code:

<select multiple="multiple">

In IE/Chrome/Firefox, it will show like the picture below. In this case, count should be 3:

in this case, count should be 3

If option count in previous case is greater than 4, it still shows 4 visible lines. In this case, count should be 4:

in this case, count should be 4

Is there a good way, other than using if...else..., to get the visible options' count of select tag, in any circumstances?

FYI, I'm developing a test software to do functional testing for customers' website, so I'm not able to modify code of the web page.


I hope I understood correctly:

 var maxVisibleCount = Math.floor(containerHeight / optionHeight);
 var actualCount = $(this).children('option').length;
 var result = (maxVisibleCount > actualCount) ? actualCount : maxVisibleCount;

live demo:

edit: sorry, I have not seen that you are not using jQuery: