简体   繁体   中英

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:

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

Below are the alternatives i have already tried:

var select = document.getElementById('animalList');
var len = select.options.length;

I get the result as 0.

$("#animalList :selected").length;

I get the result as 0.

To get the count of a select element using multiselect , make sure your code looks like the following :

 $(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.

You can get the length using the following method

  var len = 0;
  if($("#animalList").val()!=null){
   len = $("#animalList").val().length;
  }

WORKING FIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM