materangai
materangai

Reputation: 109

Javascript count selected radio button attributes

I'm trying to count the attribute on all selected radio buttons. Using alert, it does find the correct values (e.g. 900, 4680) but doesn't add them together.

Any help would be appreciated, I've probably been staring at it for too long :)

var selectedoptions;
$('input[type=radio]').change(function() {
  $("input[type=radio]:checked").each(function( index ){
    var selectedoption = $(this).attr('data-price');
    var selectedoptions = selectedoptions + selectedoption;
  });
});

Upvotes: 0

Views: 208

Answers (2)

mgarcia
mgarcia

Reputation: 6325

If you want to sum the total value of data-price attributes for the selected radio buttons, you can try with:

$('input[type=radio]').change(function() {
  // Start at zero value (if any of the radios is checked).
  var selectedoptions = 0;
  $("input[type=radio]:checked").each(function( index ){
    var selectedoption = $(this).data('price'); // Read the value as a number
    selectedoptions += selectedoption;
  });

  // Here you have in selectedoptions the total price.
});

Upvotes: 1

Message Akunna
Message Akunna

Reputation: 79

$("input[type=radio]").change(function() {
  var selectedoptions = 0;
  $("input[type=radio]:checked").each(function(index) {
    var selectedoption = $(this).attr("data-price");
    selectedoptions = parseInt(selectedoptions) + parseInt(selectedoption);
  });
  //alert(selectedoptions); get your selectedoptions value here
});

you need to parse your data-price value to int and no need to reinitialise your selectedoptions.

Upvotes: 0

Related Questions