这是我之前提问的后续问题:Displaying Selected Values in Drop-Down List With Multple = On
提供的帮助允许我在修改它们时捕获所选的值,但是当我第一次加载页面时,我无法弄清楚如何捕获初始值(选中)。
function myFunction() {
var x = $('select[name=Car]').val()
$('#demo').html("You selected: " + x.join(", "))
}
$('select[name=Car]').change(function() {
myFunction();
});
$('select[name=Car]').load(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 name="Car" multiple="on" size="5">
<option value="Audi">Audi
<option value="BMW" selected>BMW
<option value="Mercedes">Mercedes
<option value="Volvo" selected>Volvo
</select>
<br>
The car is:
<p id="demo"></p>
https://jsfiddle.net/2gq824q2/18/
我想要初始值,在这种情况下,宝马和梅赛德斯在页面加载时显示,然后在进行备用选择时进行更改。
答案 0 :(得分:1)
不要使用.load
- 只需在页面加载时调用myFunction
(页面加载后):
$(document).ready(function() {
myFunction();
});
https://jsfiddle.net/2gq824q2/19/
.load
用于在您的网页中加载其他页面。
答案 1 :(得分:0)
我最终与原始代码略有偏差,只想回馈。
<script>
function showDropDownValues() {
var str = "";
$( "select[name=Car] option:selected" ).each(function() {
str += $( this ).text() + ", ";
});
$('#demo').html("You selected: " + str);
};
$( "select[name=Car]" ).change(function() {
showDropDownValues();
});
showDropDownValues();
</script>
<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 name="Car" multiple="on" size="5">
<option value="Audi">Audi Car</option>
<option value="BMW">BMW Car</option>
<option value="Mercedes" selected>Mercedes Car</option>
<option value="Volvo">Volvo Car</option>
</select>
The car is:
<p id="demo"></p>