Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
159
rated 0 times [  162] [ 3]  / answers: 1 / hits: 8181  / 10 Years ago, fri, march 7, 2014, 12:00:00

I have an issue with the data which is sent from a drop down menu, the selector only returns a single value, even when multiple values are selected. I have searched online for a solution to this, but they all use PHP, JQuery or some method outside the scope of the course I am taking; to capture multiple selected items. I have tried .value of the individual options, but that returns all of the options rather than just the ones which are selected. Is there some kind of trick to sending multiple values?



Here is my code for the menu. For example If I select JAVA PROGRAMMING, NETWORKS and VIDEO GAMES, only JAVA PROGRAMMING is sent.



<select multiple id=CK_Expertise>
<option id=CK_Exp1 value=Java programming>JAVA PROGRAMMING</option>
<option id=CK_Exp2 value=Networks>NETWORKS</option>
<option id=CK_Exp3 value=Video game programming>VIDEO GAMES</option>
<option id=CK_Exp4 value=Accounter>ACCOUNTER</option>
<option id=CK_Exp5 value=Help Desk>HELPDESK</option>
<option id=CK_Exp6 value=C++ programming>C++</option>
<option id=CK_Exp7 value=Programming>PROGRAMMING</option>
</select>


I have also tried using the Select Object in the DOM, http://www.w3schools.com/jsref/dom_obj_select.asp
which has a few methods for accessing the options in the dropdown menu. One method in particular called selectedIndex, seemed to be what I am looking for, however it only returns the the index of the first selected option, instead of all of the selected options.

Is there a simple solution to this using just Javascript and the DOM?



Thanks
- Chris


More From » html

 Answers
26

Get the options, iterate and check if they are selected, and add the values to an array



var select = document.getElementById('CK_Expertise'),
options = select.getElementsByTagName('option'),
values = [];

for (var i=options.length; i--;) {
if (options[i].selected) values.push(options[i].value)
}

console.log(values)


FIDDLE



or being a little more fancy



var select = document.getElementById('CK_Expertise'),
values = Array.prototype.filter.call(select.options, function(el) {
return el.selected;
}).map(function(el) {
return el.value;
});

console.log(values)


FIDDLE


[#47072] Thursday, March 6, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shylaelisan

Total Points: 37
Total Questions: 94
Total Answers: 110

Location: Angola
Member since Tue, May 5, 2020
4 Years ago
;