Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

javascript - Wait until an element has a value - not just exists

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...