0

I have a country drop down, and on change of it I return a div containing the same country drop down with additional fields.

I replace this entire div using the below code. But after the replace of div is done, the on change event stops working further. How can I fix this ?

    $("#country).on("change", function(){
        var str = $("#myform").serialize();
        $.ajax({
            type: 'POST',
            data:str,
            url:'../changeme',
            success: function(data){

                debugger;

                var html = $.parseHTML(data);
                var arrSelector = $(html).find('div[data-refresh=true]');
                var i;
                for(i=0;i<arrSelector.length;i++)
                {

                    $('#' + arrSelector[i].id).replaceWith($($(data)).find('#' + arrSelector[i].id));
                }
            },
            done:function(data){

            },
            error:function(data){

            },
            complete:function(data){

            }
        });
    });
},
Novice User
  • 3,552
  • 6
  • 31
  • 56

3 Answers3

2

Events won't get called on dynamically created html through the normal means. Use the following instead, and it should get called even after you replace the div containing the country dropdown:

$(document).on('change', '#country', function() { ... });
Kai
  • 3,803
  • 1
  • 16
  • 33
1

You have several choices

Don't replace whole element, just replace it's contents. WHen you replace an element it's event bindings are lost

-OR-

Delegate event handler

 $(document).on('change',  '#country', function(){
    /* same code you already have*/
  })
charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

Try to put the whole onChange event code in a init function and call this function every time you replace your div.

function initOnChange() {
  $("#country).on("change", function(){ 
    ...
    success: function(data){
      ...
      initOnChange();
      ...
    }
    ...
  });
}
iMx
  • 846
  • 1
  • 9
  • 23