Martin Zhai Martin Zhai - 7 months ago 17
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">
<option>text1</option>
<option>text2</option>
<option>text3</option>
</select>


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.

Answer

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: https://jsfiddle.net/md13qq0d/

edit: sorry, I have not seen that you are not using jQuery: https://jsfiddle.net/md13qq0d/2/