Pavel Valeriu Pavel Valeriu - 3 months ago 10
HTML Question

How to dynamically check if select field has data

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));
});
}

Answer

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>

Comments