Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript does not work on returned ajax results

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading