I am trying to retrieve a variable from an if statement nested in a jquery .each function:
var radioAmount;
$('div.amount').each(function() {
var input = $(this).find('input[type="radio"]');
if(input.is(':checked')) {
radioAmount = input.attr('value');
} else {
radioAmount = $('#other-amount').val();
}
});
console.log(radioAmount);
I want radioAmount to return the input value outside of the .each function, but it returns undefined.
I'm sure this should be fairly straight forward and has to do with variable scope but I can't work out what I'm doing wrong.
Or maybe this is the wrong approach completely.
#other-amountexist? Is it a form element of some sort? Does it have a value?radioAmountisundefined, then there is something else going on that you are not showing us. Possibilities are thatradioAmountis not defined in a high enough scope (outside the.each()callback) or that you're doing this inside some async function and expectingradioAmountto get returned from that. Also, why use an.each()loop if you just want one value forradioAmount- that doesn't make sense to me as it can only have one value, but you're iterating over potentially many items and resetting the value over and over. If you only want one value, then pick one of the divsinputdoesn't have avalueattribute or$('#other-amount')doesn't exist or doesn't have a value.eachhandler. Check if$('div.amount')returns anything.