I have 4 selects. Using Javascript, I determine what options to display within these selects. When a select option is selected, I also trigger a change event to auto populate the additional select options. It is pretty hard to explain what exactly is happening so I have set up a JSFiddle. I have only done a little demonstration here using three selects.
var getSelectedYear = function() { return $("#year option:selected").val(); }; var getSelectedProduct = function() { return $("#product option:selected").val(); }; $('#year').change(function() { $("#year").css('border-color', '#ccc'); $("#product option").addClass("hide"); $("#product option.year-" + getSelectedYear()).removeClass('hide'); $("#product").removeClass('hide'); var first_val = $("#product option:not('.hide')").first().val(); $("#product").val(first_val); $("#product").trigger("change"); triggerImageChange(); }); $('#product').change(function() { $("#type option").addClass("hide"); $("#type option.year-" + getSelectedYear() + ".product-" + getSelectedProduct()).removeClass('hide'); $("#type").removeClass('hide'); var first_val = $("#type option:not('.hide')").first().val(); $("#type").val(first_val); $("#type").trigger("change"); triggerImageChange(); }); var triggerImageChange = function() { $.ajax({ type: "get", url: "./" }).done(function(data){ }); }; <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="form-group"> <label>Year</label> <select class="form-control" id="year"> <option value=""></option> <option value="2016">2016</option> </select> </div> <div class="form-group productGroup"> <label>Product</label> <select class="form-control hide" id="product"> <option value=""></option> <option value="Option1" class="year-2016 hide">Option1</option> <option value="Option2" class="year-2016 hide">Option2</option> </select> </div> <div class="form-group productGroup"> <label>Type</label> <select class="form-control hide" id="type"> <option value=""></option> <option value="Option1" class="year-2016 product-Option1 hide">Option1</option> <option value="Option2" class="year-2016 product-Option1 hide">Option2</option> </select> </div> Now within a change event, I also make an Ajax call. This is triggered via
triggerImageChange(); I have included this function within the fiddle. My problem is this. I need to trigger the change event to prepopulate the additional selects. However, this event causes the ajax call to be fired multiple times. You can see this within the console. So if you select the year, the fiddle will make 2 ajax calls because the triggerImageChange is being called twice. When I have 4 selects, it makes 4 ajax calls.
Is there any way to stop this from happening?
Thanks