Get multi-select value - No jQuery

In each relevant "question that [my] answer may already have" uses jQuery, which I do not use.

So, is there any easy way to get the values โ€‹โ€‹of the selected options in the <select multiple> or do I need to look at all the parameters to see which ones are selected and manually build the array?

Side question: Which browsers do not support selectElement.value and instead require selectElement.options[selectElement.selectedIndex].value ?

+4
source share
3 answers

You can use select.selectedOptions . However, this returns an HTMLCollection , so you still need to clear it to get a string array. http://jsfiddle.net/9gd9v/

 <select multiple> <option value="foo" selected>foo</option> <option value="bar">bar</option> <option value="baz" selected>baz</option> </select> 

and

 var select = document.querySelector("select"); var values = [].map.call(select.selectedOptions, function(option) { return option.value; }); 
+3
source

If you need to go through the loop and grab the selected values, you can use something like this:

 function loopSelected() { var txtSelectedValuesObj = ""; var selectedArray = new Array(); var selObj = document.getElementById('selectID'); var i; var count = 0; for (i=0; i<selObj.options.length; i++) { if (selObj.options[i].selected) { selectedArray[count] = selObj.options[i].value; count++; } } txtSelectedValuesObj = selectedArray; alert(txtSelectedValuesObj); } 

You can view the example HERE adapted from this example .

.

0
source

You can also simply track selected parameters with the onchange event in real time and collect them whenever you want. I admit that this is still a cycle, but at least you do not do it every time you need to get the selected parameters, and it has the added bonus of being simple (the time will come for the search, anyway ...). Working fiddle: http://jsfiddle.net/cyg9Z/

 var Test; if (!Test) { Test = { }; } (function () { Test.trackSelected = function (e) { var selector = document.getElementById('selector'), selected = [], i = 0; for (i = 0; i < selector.children.length; i += 1) { if (selector.children[i].selected) { selected.push(selector.children[i].value) } } selector.selMap = selected; }; Test.addListeners = function () { var selector = document.getElementById('selector'), tester = document.getElementById('tester'); selector.onchange = Test.trackSelected; tester.onclick = Test.testSelected; }; Test.testSelected = function () { var div = document.createElement('div'); div.innerText = document.getElementById('selector').selMap.join(', '); document.body.appendChild(div); }; Test.addListeners(); }());โ€‹ 
0
source

Source: https://habr.com/ru/post/1437040/


All Articles