How to compare sum the values of radio buttons >=3

Viewed 32

Help please. I have the sum value with different names in one div and need to do " if sum of all values (0+1+6 or 1+1+2 etc) >= 3 do * 3000, else do * 4000 (instead of * 3000) " I tried adding this code but it doesn t work correctly. Can t understand why. I m not professional sorry Here s https://codepen.io/evg33/pen/OJvVJMe my code

    jQuery(function ($) { 
$('input[type=radio]').each(function(){
  $(this).change(calculate);
});

function calculate() {
  var result = 0;
  $('input[type=radio]:checked').each(function(){
      
      const val = Number($(this).val());
      result += val * (val >= 3 ? 3000 : 4000);

  });
  
  $("#result").html(result);
}

    });
<div><label class="radio">
      <input type="radio" 
       name="one" value="0">
    </label>
 
<label class="radio">
      <input type="radio" 
       name="one" value="1">
    </label>
 
<label class="radio">
      <input type="radio" 
       name="two" value="1">
    </label>
 
<label class="radio">
      <input type="radio" 
       name="two" value="6">
    </label>
 
<label class="radio">
      <input type="radio" 
       name="three" value="2">
    </label>
 
<label class="radio">
      <input type="radio" 
       name="three" value="7">
    </label>
</div>
<span id="result">- </span>

This code works good (so I guess the problem is not in html). All sums are correct


    jQuery(function ($) { 
$('input[type=checkbox]').each(function(){
  $(this).change(calculate);
});

function calculate() {
  var result = 0;
  $('input[type=checkbox]:checked').each(function(){
      result += Number($(this).val()) * 3000;
  });
  
  $("#result").html(result);
}

    });
1 Answers

To apply the multiplication to the total value you need to first calculate the total from the selected radio inputs. Then you can work out the factor to be applied.

jQuery($ => {
  let calcTotal = () => {
    let total = $radio.filter(':checked').get().reduce((t, el) => t + +el.value, 0);
    let factor = total >= 3 ? 3000 : 4000;
    return total * factor;
  }

  let $total = $('#result');
  let $radio = $(':radio').on('change', () => {
    $total.text(calcTotal());
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div>
  <label class="radio">
   <input type="radio" name="one" value="0"> 0
  </label>
  <label class="radio">
   <input type="radio" name="one" value="1"> 1
  </label><br />

  <label class="radio">
    <input type="radio" name="two" value="1"> 1
  </label>
  <label class="radio">
   <input type="radio" name="two" value="6"> 6
  </label><br />

  <label class="radio">
   <input type="radio" name="three" value="2"> 2
  </label>
  <label class="radio">
    <input type="radio" name="three" value="7"> 7
  </label>
</div>
<span id="result">- </span>

Related