Skip to content Skip to sidebar Skip to footer

Displaying Selected Values In Drop-down List With Multple = On

I'm trying to display ALL selected values in a drop down list. The code shown below works to display only the first value however I'm struggling on understanding how to get it to

Solution 1:

Why not use jQuery when you can?

functionmyFunction() {
    var x = $('#car').val()
    $('#demo').html("You selected: " + x.join(", "))
}
$('#car').change(function() {
  myFunction();
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><p>Select a new car from the list.</p><selectid="car"name="Car"multiple="on"size="5"><optionvalue="Audi">Audi
  <optionvalue="BMW">BMW
  <optionvalue="Mercedes">Mercedes
  <optionvalue="Volvo">Volvo
</select><br>
The car is:
<pid="demo"></p>

Solution 2:

Here you go: https://jsfiddle.net/2gq824q2/15/

functionmyFunction() {
    var sSelected = '';
    [].forEach.call(  document.querySelectorAll('#Car :checked')  , function(elm){
       	if(sSelected !== '') sSelected += ', ';
    	 sSelected += elm.value;
		})
    document.getElementById("demo").innerHTML = "You selected: " + sSelected;
}
<p>Select a new car from the list.</p><selectid="Car"multiple="on"size="5"onchange="myFunction()"><optionvalue="Audi">Audi
  <optionvalue="BMW">BMW
  <optionvalue="Mercedes">Mercedes
  <optionvalue="Volvo">Volvo
</select><br>
The car is:
<pid="demo"></p>

I updated the function, and note the select now has an ID.

Post a Comment for "Displaying Selected Values In Drop-down List With Multple = On"