Dogsled Dogsled - 3 months ago 6
jQuery Question

Display Selected Values in Drop Down on Page Load (Multiple=on)

This is a follow-up to my earlier question: Displaying Selected Values in Drop-Down List With Multple = On

The help provided allowed me to capture the selected values when they were modified however I could not figure out how to capture the initial values (selected) when the page first loaded.

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/

I would like the initial value(s), in this case BMW and Mercedes to be shown when the page is loaded and then be changed if alternate selections are made.

Answer

Dont use a .load - just simply call myFunction on page load (after the page has been loaded):

$(document).ready(function() {
    myFunction();
});

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

.load is for loading another page within your page.

Comments