0

Pls can someone help me with code? I want to change option in select after page is loaded cuz form is generated with DOM.

I dont know why - with "onClick" is it working:

$(window).load(function() { 
 $( "#target" ).click(function() {
    $("#filter_1 option[value=11]").attr('selected', 'selected').trigger('change');
 }); 
});

But i want to change select without click and this is not working:

$(window).load(function() { 
    $("#filter_1 option[value=11]").attr('selected', 'selected').trigger('change');
});

What am i doing wrong?

Edit - i found out that all "options" are not there yet, when i'm trying to change them. Working solution is:

$(function() {

  function changeOption() {
    $("#filter_1 option[value=11]").attr('selected', 'selected').trigger('change'); 
  }

  setTimeout(function(){
    changeOption();
  }, 500);

});

Is there any better solution than Timeout?

Spouter
  • 11
  • 6
  • Maybe you meant `$(window).on( "load"...`? Use `$(document).ready(function() { ...` to access the DOM after it's been loaded. https://learn.jquery.com/using-jquery-core/document-ready/ - if you wan to wait for all the images and iframes to load, you can use `$(window).on( "load", function() { ... })` https://stackoverflow.com/questions/4584373/difference-between-window-load-and-document-ready-functions/4584475 – Kinglish Dec 09 '21 at 00:33

1 Answers1

0

There are several issues in your code.

First $(window).load(func... is deprecated. Use $(function(){... which is shorthand for $(document).ready(function instead

Next, there is not change event on <option> you need to trigger it on the parent <select>

Finally you can simplify the attr('selected') on the option by just setting value of the parent <select>

$(function() {

  // change event listener
  $('#filter_1').change(function() {
    console.log('Changed value to: ', this.value);
  })

  // set the value and trigger the change
  $('#filter_1').val(11).change()

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="filter_1">
  <option value=""> ---- </option>
  <option value="10"> 10 </option>
  <option value="11"> 11 </option>
  <option value="12"> 12 </option>
</select>
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • Your solution is were not working too. So i found out that all "options" are generated in on.load. And when i'm trying to change option the options are not there yet. – Spouter Dec 09 '21 at 15:12
  • Still simpler to set the select value once the options do exist – charlietfl Dec 09 '21 at 16:36