Passing Result from jQuery Embedded function to Parent JavaScript Function For Return?

894359
894359 used Ask the Experts™
on
I don't know why the embedded jQuery function below is not returning the value to my JS var? I do get the expected value in console.log(" >>>> FINAL RESULTS RETURNED : " + results);
function _dtmGetCurrResults(){
	    var results = [];
	    $(function() {
            $('[class*="solid-shape-large-rating-"]').each(function(i, e) {
                var result = this.className.match(/solid-shape-large-rating-(.*?)\s+/);
                results.push(result[1]); 
            });
        results = results.join("|");
        console.log(" >>>> FINAL RESULTS RETURNED : " + results);
		});
		return results;
	};
var myResults = _dtmGetCurrResults();

Open in new window



Thanks!
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
The way you've defined your internal function:

$(function() {
   ...

Open in new window

... is the shorthand for the dom.ready block in jQuery. This means that execution will be deferred until the DOM is ready. However, your call to _dtmGetCurrResults() will fire as soon as it's hit, which is likely to be before the DOM is ready. You're effectively getting the results of your function BEFORE the internal one has had a chance to run. Basically, it's doing this:

var results = [];
return results
... some time later run $(function() { ... }

Open in new window

You need to change things around a little:

function _dtmGetCurrResults(){
    var results = [];
    $('[class*="solid-shape-large-rating-"]').each(function(i, e) {
        var result = this.className.match(/solid-shape-large-rating-(.*?)\s+/);
        results.push(result[1]); 
    });
    results = results.join("|");
    console.log(" >>>> FINAL RESULTS RETURNED : " + results);
    return results;
};

$(function() {
    var myResults = _dtmGetCurrResults();
}

Open in new window

We've now moved the call to _dtmGetCurrResults() into the dom.ready, so that will fire once the DOM is loaded and it'll return the correct results. Depending on how and when you need to use myResults, you may need to edit the scope.

Author

Commented:
Thank you for your help. I'm obviously not a person that uses jQuery!  Much appreciated!
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
No worries. Glad I could help

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial