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);
You cannot return variable value from jQuery event function. To understand the reason, let us see how data is passed, which was created in the event handler of a button click.
To return a value from a function, you must include a return statement, followed by the value to be returned, before the function's end statement. If you do not include a return statement or if you do not specify a value after the keyword return, the value returned by the function is unpredictable.
In jQuery, the $ sign is just an alias to jQuery() , then an alias for a function. This page reports: Basic syntax is: $(selector).action() A dollar sign to define jQuery. A (selector) to "query (or find)" HTML elements.
JavaScript passes a value from a function back to the code that called it by using the return statement. The value to be returned is specified in the return. That value can be a constant value, a variable, or a calculation where the result of the calculation is returned.
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With