-3

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?

WaWalex
  • 19
  • 5
  • Does this answer your question? [Make jquery function run on page load](https://stackoverflow.com/questions/12468374/make-jquery-function-run-on-page-load) – domsson Jan 18 '20 at 10:38

2 Answers2

1

Did you heard the jquery trigger?

$(function() {
  $('#borderColor').trigger('change')
});
doğukan
  • 23,073
  • 13
  • 57
  • 69
1

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>
Tschallacka
  • 27,901
  • 14
  • 88
  • 133