我试图在下拉列表中显示所有所选值。下面显示的代码仅用于显示第一个值,但是我很难理解如何让它显示所选的每个值。
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>
答案 0 :(得分:0)
在这里:https://jsfiddle.net/2gq824q2/15/
function myFunction() {
var sSelected = '';
[].forEach.call( document.querySelectorAll('#Car :checked') , function(elm){
if(sSelected !== '') sSelected += ', ';
sSelected += elm.value;
})
document.getElementById("demo").innerHTML = "You selected: " + sSelected;
}
&#13;
<p>Select a new car from the list.</p>
<select id="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>
&#13;
我更新了这个功能,并注意select现在有一个ID。
答案 1 :(得分:0)
为什么不尽可能不使用jQuery?
function myFunction() {
var x = $('#car').val()
$('#demo').html("You selected: " + x.join(", "))
}
$('#car').change(function() {
myFunction();
});
&#13;
<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>
&#13;