gethyn1
gethyn1

Reputation: 137

Retrieve variable from if statement nested in .each function

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

Answers (3)

gethyn1
gethyn1

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

Mark Schultheiss
Mark Schultheiss

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

jfriend00
jfriend00

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:

  1. That radioAmount is not defined in a high enough scope (outside the .each() callback)
  2. You're doing this inside some async function and expecting radioAmount to get returned from that.
  3. Perhaps input doesn't have a value attribute.
  4. Perhaps $('#other-amount') doesn't exist.
  5. Perhaps $('#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

Related Questions