Reputation: 137
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.
Upvotes: 2
Views: 131
Reputation: 137
The issue here is not the variable scope but that $('#other-amount')
is undefined.
I missed this because I thought it wouldn't matter if a radio input was checked instead.
As suggested in the comments, I have rewritten this without .each()
:
var radioAmount;
var checkedRadio = $('div.amount').find('input[type="radio"]:checked');
if(checkedRadio.length) {
radioAmount = checkedRadio.attr('value');
} else {
radioAmount = $('#other-amount').val();
}
console.log(radioAmount);
Upvotes: 1
Reputation: 34168
var radioToCheck =$('div.amount').find('input[type="radio"]:checked');
var radioAmount = radioToCheck.length ? radioToCheck.val() : $('#other-amount').val();
Assumption of $('#other-amount')
existing and being of an input type with a value.
Upvotes: 0
Reputation: 707406
I'll move my comments to an answer since guess #5 below seems to have solved it for you:
Without seeing the page and more specifics about the error, I can only guess what things could be causing what you observe. If radioAmount
is undefined
, then there is something else going on that you are not showing us. Possibilities are:
radioAmount
is not defined in a high enough scope (outside the .each()
callback) radioAmount
to get returned from that. input
doesn't have a value attribute.$('#other-amount')
doesn't exist.$('#other-amount')
doesn't have a value.P.S. Why use a .each()
loop if you just want one value for radioAmount
- 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 divs
Upvotes: 0