[英]selectedOptions.length not working in Internet explorer but works properly in chrome and firefox?
I have been working with ui.multiselect.js
which is just similar to HTML Select: 我一直在使用ui.multiselect.js
,它与HTML Select相似:
I wanted the length of the selected elements. 我想要选定元素的长度。 So i had used the below code: 所以我用下面的代码:
var selectedOption = document.getElementById('animalList').selectedOptions.length;
But it seems selectedOptions.length
is not working in IE but working properly in Chrome and Firefox 但是似乎selectedOptions.length
在IE中不起作用,但在Chrome和Firefox中正常工作
Below are the alternatives i have already tried: 以下是我已经尝试过的替代方法:
var select = document.getElementById('animalList');
var len = select.options.length;
I get the result as 0. 我得到的结果为0。
$("#animalList :selected").length;
I get the result as 0. 我得到的结果为0。
To get the count of a select
element using multiselect
, make sure your code looks like the following : 要使用multiselect
获得select
元素的数量,请确保您的代码如下所示:
$(document).ready(function() { $('button').click(function() { // jquery version var count = $("#foo :selected").length; console.log("jQuery Count: " + count); // pure javascript version var options = document.getElementById('foo').options, count = 0; for (var i=0; i < options.length; i++) { if (options[i].selected) count++; } console.log("Pure Javascript: " + count); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button>Count Selected</button><br> <select multiple id="foo"> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="opel">Opel</option> <option value="audi">Audi</option> </select>
I have included both a pure javascript version and jQuery version which are executed when you click the button. 单击按钮时,将同时执行纯JavaScript版本和jQuery版本。
You can get the length using the following method 您可以使用以下方法获得长度
var len = 0;
if($("#animalList").val()!=null){
len = $("#animalList").val().length;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.