Dogsled Dogsled - 3 months ago 8
Javascript Question

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 display each value that is selected.

function myFunction() {
var x = document.getElementsByName("Car").item(0).value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}

<p>Select a new car from the list.</p>
<select name="Car" multiple="on" size="5" onchange="myFunction()">
<option value="Audi">Audi
<option value="BMW">BMW
<option value="Mercedes">Mercedes
<option value="Volvo">Volvo
</select>
<br>
The car is:
<p id="demo"></p>


https://jsfiddle.net/2gq824q2/12/

Answer

Why not use jQuery when you can?

function myFunction() {
    var x = $('#car').val()
    $('#demo').html("You selected: " + x.join(", "))
}
$('#car').change(function() {
  myFunction();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Select a new car from the list.</p>

<select id="car" name="Car" multiple="on" size="5">
  <option value="Audi">Audi
  <option value="BMW">BMW
  <option value="Mercedes">Mercedes
  <option value="Volvo">Volvo
</select>
<br>
The car is:
<p id="demo"></p>

Comments