finding sum of prefilled fields with jquery

50 views Asked by At

I am trying to find the sum of 2 fields that were both pre filled earlier in the form based on conditionals in another script, so there is no direct input of these fields. The following code works if I directly change the value in those fields, but not if they have been previously filled.

$(document).on('change keyup blur', '#member_type', function () {
  var val = $('#member_type').val();
  if ($('#member_type').val() == 'junior') var result = 10;
  else if (($('#member_type').val() == 'senior', 'master')) var result = 15;
  $('#scDues').val(result);
  calcTotal();
});

$(document).on('change keyup blur', '#num_boats', function () {
  if ($('#num_boats').val() == '0') var result = 0;
  else if ($('#num_boats').val() == '1') var result = 10;
  else if ($('#num_boats').val() == '2') var result = 20;
  else if ($('#num_boats').val() == '3') var result = 30;
  $('#scBoatFee').val(result);
  calcTotal();
});

function calcTotal() {
  var sum = 0;
  $('.fee').each(function () {
    sum += +$(this).val();
  });
  $('#totalFee').val(sum);
}
$('.fee').keyup(function () {
  var sum = 0;
  $('.fee').each(function () {
    sum += Number($(this).val());
  });
  $('#totalFee').val(sum);
  calcTotal();
});

$(document).ready(function () {
  $('#scDues, #scBoatFee').change(function () {
    var value1 = parseFloat($('#scDues').val()) || 0;
    var value2 = parseFloat($('#scBoatFee').val()) || 0;
    $('#scTotal').val(value1 + value2);
  });
  calcTotal();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<span>Member Type</span>
<select name="member_type" id="member_type">
  <option value="">Select</option>
  <option value="junior">Junior</option>
  <option value="senior">Senior</option>
  <option value="master">Master</option>
</select>
<br><br>

<span>Number Boats</span>
<select name="num_boats" id="num_boats">
  <option value="">Select</option>
  <option value="0">0</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

<br><br>

<span>SC Dues</span>
<input type="text" value="" name="scDues" id="scDues" maxlength="12" />
<br><br>
<span>Boat Fee</span>
<input type="text" value="" name="scBoatFee" id="scBoatFee" maxlength="12" />
<br><br>
<span>Total SC</span>
<input type="text" value="" name="scTotal" id="scTotal" />

How can I make this work?

I tried removing the whole line with the .change(function () , but then it doesn’t work at all.

0

There are 0 answers