I have a set of dynamic dropdown menus which are populated using JQuery/Javascript via a javascript array. As you select different parent dropdown values the children change. Fairly basic stuff.
We have an issue where a another javascript function needs to use a child dropdownlist value in order to process.
As the scripts run asyncronously there are situations where the value is not populated by the time the second script needs the value.
I was hoping to use setTimeout to 'wait' for the value to be set by the first script before continuing the second script.
I lifted the code below from another thread but it only ever seems to wait 'once', it never waits 50ms and then wait again if the condition is not set.
var waitForEl = function(selector, callback) {
if (($('#'+selector).val())) {
console.log('good to go');
callback();
} else {
setTimeout(function() {
console.log('paused for thought');
waitForEl(selector,callback);
},50);
}
};
$('[id^="currentcontainersizeid"]').each(function() {
thisId = $(this).attr('id').replace(/^D+/g, "")
if (($('#currentcontainersizeid'+thisId).length > 0) && ($('#currentcontainersizeid'+thisId).val())) {
waitForEl('containersizeid'+thisId, function() {
console.log('FIRE TRIGGER');
$('#containersizeid'+thisId).trigger('change');
});
}
});
I am not sure whether it is my test that is wrong or the timeout logic. Should I be checking whether the element is 'selected' rather than has a 'val'. If so how would I do that?
Does the code above look correct to achive what I want?
Thoughts/help appreciated.
question from:
https://stackoverflow.com/questions/65917578/wait-until-an-element-has-a-value-not-just-exists 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…