0

HTML:

<select id="g_contracts">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

JS:

$(document).ready( function() {
    $("#g_contracts").trigger("change");

    $("#g_contracts").on("change", function() {
         alert(44);
    });
});

Well, alert happens when I directly change selector, but trigger("change") not causes anything.

What I missed ?

https://jsfiddle.net/c7t398mf/2/

Ed Bangga
  • 12,879
  • 4
  • 16
  • 30
Oto Shavadze
  • 40,603
  • 55
  • 152
  • 236

2 Answers2

1

Trigger the event after assigning the event handler to the element:

$(document).ready( function() {
  $("#g_contracts").on("change", function() {
    alert(44);
  });
  $("#g_contracts").trigger("change");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="g_contracts">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>
Mamun
  • 66,969
  • 9
  • 47
  • 59
1

The trigger() method triggers the specified event and the default behavior of an event (like form submission) for the selected elements.

    $(document).ready( function() {
    
      $("#g_contracts").on('change',function(){
        alert("44");
      });

      $("#g_contracts").trigger('change');

    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <select id="g_contracts">
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>
Shivani Sonagara
  • 1,299
  • 9
  • 21