30

I've created a function to iterate through a UL/LI. This works perfectly, my problem is returning the value to another variable. Is this even possible? What's the best method for this? Thanks!

function getMachine(color, qty) {
    $("#getMachine li").each(function() {
        var thisArray = $(this).text().split("~");
        if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
            return thisArray[3];
        }
    });

}

var retval = getMachine(color, qty);
7
  • 1
    It's possible and that's how I would do it. Are you not getting a value returned? Commented Jul 28, 2011 at 14:56
  • Your code seems correct, are you able to run Firebug and see if the Console lists anything? Commented Jul 28, 2011 at 14:56
  • 3
    return won't work this way in $.each. return will just exit the foreach loop. Commented Jul 28, 2011 at 15:00
  • This doesn't work because return thisArray[3] only returns from the .each() inner function, it doesn't return from the getMachine function. As other posters have shown, you need to set thisArray[3] to a local variable and return(false) from the inner function to stop the .each() iteration and then you can return that inner variable from getMachine. Commented Jul 28, 2011 at 15:03
  • 1
    Return should actually be false or true for an $.each(). Where false is like a break and true is like a continue. Commented Jul 28, 2011 at 15:03

2 Answers 2

54

I'm not entirely sure of the general purpose of the function, but you could always do this:

function getMachine(color, qty) {
    var retval;
    $("#getMachine li").each(function() {
        var thisArray = $(this).text().split("~");
        if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
            retval = thisArray[3];
            return false;
        }
    });
    return retval;
}

var retval = getMachine(color, qty);
Sign up to request clarification or add additional context in comments.

Comments

19

The return statement you have is stuck in the inner function, so it won't return from the outer function. You just need a little more code:

function getMachine(color, qty) {
    var returnValue = null;
    $("#getMachine li").each(function() {
        var thisArray = $(this).text().split("~");
        if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
            returnValue = thisArray[3];
            return false; // this breaks out of the each
        }
    });
    return returnValue;
}

var retval = getMachine(color, qty);

1 Comment

You need to add return false; inside of if statement to break from each() after the assignment.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.