1

I have a select field that is populated with data after a callback succeeded and I need to call a function when this happens.

I tried to use the jQuery on .change but this is fired only after I select another option, not when the select field is populated.

Is there a way to dynamically check if a select field gets some values?

This is what I've done so far:

$('select').on('change', function() {
   // Do something
});

This is how I populate my select list (I'm using google apps script):

  function onMetricsSuccess(selectList) {
    $.each(selectList, function(key, value) {   
      $('select')
        .append($("<option></option>")
        .attr("value",value)
        .text(value)); 
      });
  }
George G
  • 7,443
  • 12
  • 45
  • 59
Valip
  • 4,440
  • 19
  • 79
  • 150

2 Answers2

1

You can do this,

Note:I added an ID to apply the event to specific select

// After populating the select list

$(document).ready(function(){
    
    $('#myDropdown').on('change', function(){
      alert('Yay I was changed !!');
    });
    populateSelect();
});


function populateSelect(){
  var select = $('#myDropdown');
   select.append(new Option('Im a text', 'text'));
   select.append(new Option('Im a number', 'number'));
  
   $('#myDropdown').trigger('change');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="myDropdown"></select>
Anonymous Duck
  • 2,942
  • 1
  • 12
  • 35
  • Thank you! This works, but I need to call the `populateSelect()` function only after the select list is populated...right now it is called when the page loads even if there is no value in the select list – Valip Aug 10 '16 at 09:07
  • @PavelValeriu this is an example only since I don't know how you populated the list, so in your case just move this line `$('#myDropdown').trigger('change');` on the end of onMetricsSuccess function – Anonymous Duck Aug 10 '16 at 09:13
0

To check whether the dropdown options are populated or not try this:

var length = $('#mySelectList').children('option').length;
if(length > 0)
{
   // populated successfully
}
Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59