Alex G Alex G - 3 months ago 4
jQuery Question

Length of visible option elements always shows `0`

I only want to know the

length
of visible
option
elements.

Same value for all elements is must have.

The following code always shows
0
.

Please help.



$('select option[data-id=2]').hide();
var exist = $('select option[value=1]:visible').length;
alert(exist);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value='1'>test 1</option>
<option value='1' data-id='2'>test 2</option>
</select>





Screenshot:
screenshot

Answer

$('select option[data-id=2]').hide();

var length = $('select option[value=1]').filter(function() {
     return $(this).css('display') != 'none';
}).length;

alert(length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
  <option value='1'>test 1</option>
  
  <option value='1' data-id='2'>test 2</option>
</select>

Try this way of checking. Filter it then check if display block then do the length counting

Comments