Home > other >  How to trigger event on windows load
How to trigger event on windows load

Time:10-05

i like to execute $('select[name="order_id"]').change() on windows load but is not doing anything

if i debug this is browser console i can see script is execute $('select[name="order_id"]').change() but nothing happen is not sending ajax request

if i manually change the select or paste in browser console $('select[name="order_id"]').change() everything work fine

any ideas how to fix it ? i also tried with .trigger('change') but is same issue

        window.addEventListener("load", function (e) {
      
      <?php if ($logged): ?>
      
      $('select[name="order_id"]').change()
      
      $('select[name="order_id"]').change(function(){
        var order_id = $(this).val();
        isSelectedOrder = true

        $.ajax({
              url: 'index.php?route=return/getProductsByOrderId',
              data: {order_id:order_id},
              dataType: 'json',
              type: 'POST',
              beforeSend: function(){

                .......
                .....
                ..
                .

        <?php endif; ?> 
        
      }) 

CodePudding user response:

Your problem is that you trigger the change() before attaching the event, all you need to do is move the trigger of the change() to after you attach the event.

window.addEventListener("load", function (e) {
      <? php if ($logged): ?>
      
      $('select[name="order_id"]').on('change', function () {
            var order_id = $(this).val();
            isSelectedOrder = true

            $.ajax({
                url: 'index.php?route=return/getProductsByOrderId',
                data: { order_id: order_id },
                dataType: 'json',
                type: 'POST',
                beforeSend: function () {

                .......
                },
            });
        });

        $('select[name="order_id"]').change()

    <? php endif; ?> 
});

CodePudding user response:

You can use this code block

$( document ).ready(function() {
    console.log( "ready!" );
});

ref: https://learn.jquery.com/using-jquery-core/document-ready/

  • Related