dhiraj
dhiraj

Reputation: 436

Change event inside ajax success function

I am trying to call the ajax request inside change event looks like following,

$("#htmlSelector").change(function(){
$.ajax({
    url: '/basedata/',
    type: "GET", 
    data: {selectedData: $("#htmlSelector").val()}
    success: function(res){
       var column = res.column;
       $(".htmlSelector2").change(function(){
          addData(column, $(this).val());
      }
    }
  })
})

For the first change on htmlSelector element, it is ok. But when I change it again, the addData function will run two times, which is not desire case for me. I want to run the addData function only one time with the latest column value from ajax only?

Upvotes: 1

Views: 1156

Answers (1)

Mayank Patel
Mayank Patel

Reputation: 1571

It looks like your event is getting bound multiple times.

Try to unbind the event and rebind again like this.

$("#htmlSelector").change(function(){
$.ajax({
    url: '/basedata/',
    type: "GET", 
    data: {selectedData: $("#htmlSelector").val()}
    success: function(res){
       var column = res.column;
       $(".htmlSelector2").unbind('change');
       $(".htmlSelector2").change(function(){
          addData(column, $(this).val());
      }
    }
  })
})

Let me know in case it doesn't work.

Upvotes: 1

Related Questions