jQuery fire function when previous <select> is enabled

- 1 answer

Ad

I have three <select> elements.

  • Select 1
  • Select 2
  • Select 3

Select 1 is enabled, while Select 2 & 3 are disabled by default, as they depend on their "previousSibling".

Select 1 is populated with options coming from a MySQL query. When one of this options is selected, the following code enables Select 2 and populates it with an AJAX call:

$("#select1").change(function(){
       var id = $(this).val();
       var dataString = 'id='+ id;
       $.ajax({
           type: "POST",
           url: './php/selectProperty.php?nocache=' +
             (new Date()).getTime(),
           data: dataString,
           cache: false,
           async: false,
           success: function(html){
                 $("#select2").html(html);
                 $('#select2').prop("disabled", false);// Element(s) are now enabled.
           }});
});

Although Select3 follows the same methodology ($("#select2").change(function()...) it is not being enabled or populated, as I can imagine that the change method expects an explicit change from the user's side and not just a change in the DOM. Because sometimes Select 2 has only one option, change() will never fire.

Is there an alternative method for firing the population of Select 3 and enable it? For example, when Select 2 lose its disabled property?

Ad

Answer

Ad

1st: you need to use .on()

$("#select2").on('change',function(){});

or

$("body").on('change', '#select2' ,function(){});

but I think the .on() will work

2nd: to make just one code for all of them

$('select[id^="select"]').on('change',function(){
  var ThisIt = $(this);
  var id= ThisIt.val();
  var getNextSelect = ThisIt.next('select[id^="select"]');
  var dataString = 'id='+ id;
  $.ajax({
    type: "POST",
    url: './php/selectProperty.php?nocache=' + (new Date()).getTime(),
    data: dataString,
    cache: false,
    async: false,
    success: function(html){
      getNextSelect.html(html).promise().done(function(){
            getNextSelect.prop("disabled", false); // Element(s) are now enabled.
      });
    } 
  });
});
Ad
source: stackoverflow.com
Ad