Neeraj Pathak
Neeraj Pathak

Reputation: 759

change event not stopping

I am trying to change Country event when (ddlcountry) select value but the change event fire continuously.

$(document).ready(function () {
    $('#ddlCountry').on('change', function () {
        if ($('#ddlCountry option:selected').index() > 0) {
            getStateDetails();
        }
    });
    $('#ddlState').on('change', function () {                
        if ($('#ddlState option:selected').index() > 0) {
            getCityDetails();
        }
    });
});

$('#ddlCountry').val(data.CountryID).trigger('change');
$('#ddlState').val(data.StateID).trigger('change');

How can I stop this.

Upvotes: 0

Views: 136

Answers (2)

Himanshu Upadhyay
Himanshu Upadhyay

Reputation: 6565

I think you would be getting data variable's value in getStateDetails and getCityDetails functions, and so following two lines are getting new values each time:

$('#ddlCountry').val(data.CountryID).trigger('change');
$('#ddlState').val(data.StateID).trigger('change');

And they trigger change event then. And again when you really select any value from these dropdown, the jquery change event triggers and calls those above mentioned functions and then the cycle goes on and on.

To pass value of selected option of dropdowns you can code like this:

$('#ddlCountry').on('change', function () {
    if ($('#ddlCountry option:selected').index() > 0) {
        getStateDetails($(this).val());
    }
});
$('#ddlState').on('change', function () {                
    if ($('#ddlState option:selected').index() > 0) {
        getCityDetails($(this).val());
    }
});

Pass their value as an argument in the functions.

Upvotes: 1

Bannarisamy Shanmugam
Bannarisamy Shanmugam

Reputation: 128

Generally while continiously triggering events we can use following to avoid it:

  1. Use off() and on() in a single statement(i.e .off().on(function(){})).
  2. Moving the Javascript or Jquery code to other js file.

Hope this helps!

Upvotes: 0

Related Questions