Reputation: 4610
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));
});
}
Upvotes: 1
Views: 116
Reputation: 26258
To check whether the dropdown options are populated or not try this:
var length = $('#mySelectList').children('option').length;
if(length > 0)
{
// populated successfully
}
Upvotes: 0
Reputation: 2978
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>
Upvotes: 1