Reputation: 13682
Is there a way I can get the length of list options in a select-dropdown HTML input tag? The list changes dynamically and I need to calculate the total number of options within the drop-down. The total options are generated dynamically, so I need a way to calculate number of option tags within an html select tag. I also need to do this in pure JS because the app I am working with will not allow me to use JQuery. (Please don't argue that with me unless there is absolutely no way to do this in pure JS.)
Needs only to be compatible with Internet Explorer.
I assume this will have to do with accessing the DOM, but I am not sure how exactly the syntax will work out.
Upvotes: 14
Views: 53134
Reputation: 111
Try this:
In the HTML file:
<select id="mySelect">
<option>Apple</option>
<option>Pear</option>
<option>Banana</option>
<option>Orange</option>
</select>
In the JavaScript file:
document.getElementById("mySelect").length;
Upvotes: 1
Reputation: 26
i did this Using JQuery
$(document).ready(function() {
$("button").click(function(){
var optionLength = $("#user option").length;
alert("length of options is : "+optionLength);
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Get length of list Options</title>
</head>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<body>
<select id="user" multiple="" size="5" class="form-control" id="participants" name="participants" style="height: 98px !important;">
<option value="1">S RAJ</option>
<option value="2"> SHARMA</option>
<option value="3">SINGH</option>
<option value="4"> ROY</option>
<option value="5">VERMA</option>
<select>
<button type="button">Get Users</button>
</body>
</html>
Upvotes: 1
Reputation: 1
<select id="lister-sort-by-options" name="sort" class="lister-sort-by">
<option value="0" selected="selected">
Movies
</option>
<option value="1">
TV Shows
</option>
<option value="2">
Morning Shows
</option>
<option value="3">
Moonlight
</option>
<option value="4">
Music
</option>
</select>
Upvotes: 0
Reputation: 29549
Since you didn't specify that you could use jQuery, try this:
HTML:
<select id="test">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
JavaScript:
document.getElementById("test").options.length
Upvotes: 40
Reputation: 7351
Select the options from the select input, then count them with length
$("#input1 option").length
Upvotes: 5