javascript - Check if drop-down has more than 1 option - Stack Overflow

admin2025-04-22  0

I have a drop down which is being populated on change of some other checkboxes, so on load the drop-down is empty(has only 1 option "Select" in it).

<select id="A" aria-invalid="false">
    <option disabled="" value="0">Select</option>
</select>

On check of check-box the value will be added to a drop-down and on un-check of a check-box value will be removed from the drop-down.

I have written a logic for that already. What I am looking for is how do I check if dropdown has any options added to it. ie. on check of a check box I want to display the dropbox if that's the first option added to it else hide the drop-down.

I have a drop down which is being populated on change of some other checkboxes, so on load the drop-down is empty(has only 1 option "Select" in it).

<select id="A" aria-invalid="false">
    <option disabled="" value="0">Select</option>
</select>

On check of check-box the value will be added to a drop-down and on un-check of a check-box value will be removed from the drop-down.

I have written a logic for that already. What I am looking for is how do I check if dropdown has any options added to it. ie. on check of a check box I want to display the dropbox if that's the first option added to it else hide the drop-down.

Share Improve this question asked Sep 29, 2015 at 4:55 ArtiArti 3,07111 gold badges74 silver badges123 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

You can use the option length;

var optionsLen = $('#A option').length;

document.write('<br />Number of Options = ' + optionsLen);
<script src="https://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="A" aria-invalid="false">
  <option disabled="" value="0">Select</option>
</select>


If you want number of options which are not disabled.

var optionsLen = $('#A option:not(:disabled)').length;

document.write('<br />Number of Options = ' + optionsLen);
<script src="https://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="A" aria-invalid="false">
  <option disabled="" value="0">Select</option>
  <option value="1">One</option>
</select>

alert($('#A option').length)

DEMO

Use the id of select as select and select the option then get the length of by using .length

you can try this one:

$(document).ready(function() {
      alert($('#A option').length)
});

DEMO

Here, this checks how many children there are, you just need to add an if condition or something similar and it's done

https://jsfiddle/z8ub6d01/

html:

<select>
    <option>Select</option>
    <option>Select</option>
    <option>Select</option>
</select>
<span id="foo"></span>

jquery/js:

var $children = $('select').children();
$('#foo').html("You have " + $children.length + " children");
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745284089a294282.html

最新回复(0)