I have the following function:
$('#borderColor').on('change', function() {
// update inventory
updateInventory(this.options[this.selectedIndex].text);
});
How can I automaticcally trigger this function when the page loads?
I have the following function:
$('#borderColor').on('change', function() {
// update inventory
updateInventory(this.options[this.selectedIndex].text);
});
How can I automaticcally trigger this function when the page loads?
Did you heard the jquery trigger?
$(function() {
$('#borderColor').trigger('change')
});
Just trigger the change event on the select on page load. This way you don't need to write duplicate code, and everything is handled at one place.
with $('#selector').trigger() you can trigger any event, like change
, click
, input
, etc... you're listening to.
With $(document).ready(function() { /** your code here **/})
you can set code you wish to run after the page has finished loading and rendering.
function updateInventory(value) {
$('#inventory').text(value);
}
$('#borderColor').on('change', function() {
// update inventory
updateInventory(this.options[this.selectedIndex].text);
});
$(document).ready(function() {
$('#borderColor').trigger('change');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="borderColor">
<option value="red">red</option>
<option value="blue" selected="selected">blue</option>
</select>
<div id="inventory">
</div>