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.
To get the count of options in a dropdown list, use the length property in JavaScript.
You will use the following command to determine if there are any options within the select box. var length = $('#selectBoxId > option'). length; console. log(length);
options. length is "the number of elements in the list of options childNodes on the select element". Technical difference, semantically slightly different, but due to how select. length has been formalised, for all intents and purposes always the same value.
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
example
Select the options from the select input, then count them with length
$("#input1 option").length
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>
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With