Home > Software design >  Javascript does not work on returned ajax results
Javascript does not work on returned ajax results

Time:05-24

I have an ajax call that returns html. This works well on changes. What does not work though is the javascript I have that does stuff based on clicks in the returned results.

The ajax call is:

    function update_order_shipping(){
      $.ajax({
         url: 'ajax_order_shipping.php',
         method: "post",
         dataType: 'html',
         success: function (result) {
             $('#shipping-method').html(result);
      },
      error: function(xhr, status, error) {
        //alert(xhr.responseText);
      }
      });
 };

This works well. Returns the exact results I need.

The issue is that these returned results also have radio buttons and on change I perform this javascript:

    $('input[name="shipping"]').change(function() {
       if($(this).is(':checked') && ( $(this).val() == 'freeamount_freeamount' ) ){
    document.getElementById('fedex_number').style.display="none";
    document.getElementById('ups_number').style.display="none";
          document.getElementById('your_shipping_conditions').style.display="none";
var shipping_method = document.getElementById('text-freeamount').innerText;
 document.getElementById('text-shipping').innerHTML = shipping_method;
var shipping_value = document.getElementById('value-freeamount').innerText;
document.getElementById('value-shipping').innerHTML = shipping_value;
    
       }
    });

Now on initial page load this works great, but the returned results which is identical html as the intial page load, the javascript fails to work. I understand it has to do with binding or something like that, but not quite sure how to implement it, so that results will always use the javascipt.

CodePudding user response:

You need to use on to bind events to dynamically created elements.

$("body").on("change", "input[name='shipping']", function(event) {   
   // stuff here 
});

"body" can be replaced with any non-dynamic element that's an ancestor of your input.

Any matching events will automatically listen for the change event, whether the element was added at the start or later.

  • Related