Search code examples
javascriptjquerycalculation

Jquery - Subtract number from 'total' field without direct input


I have a form that includes 3 text fields, none which receive direct input.

I am trying to use jQuery with conditionals to subtract 15 from the third field, and display that result in a fourth text field.

So, if either the renewal_boat_fees OR the new_boat_fees fields have 15 or more, I want to deduct 15 once from the totalFee field and display that in the final_dues field.

$(document).on(
  "change",
  "#renewal_boat_fees, #new_boat_fees, #totalFee",
  function () {
    var val2 = $("#renewal_boat_fees").val();
    var val3 = $("#new_boat_fees").val();
    var val4 = $("#totalFee").val();
    if ($("#renewal_boat_fees").val() >= 15 || $("#new_boat_fees").val() >= 15)
      var result = val4 - 15;
    $("#final_dues").val(result);
  },
);

The totalFee field fills correctly with the sum of renewal_boat_fees and the new_boat_fees, but the final_dues field does not show any result.

I don't have much experience with jQuery, so I'm not sure if I'm on the right track.


Solution

  • As you said I have a form that includes 3 text fields, none of which receive direct input.

    So seems like they are coming pre-filled and you want to check and do stuff based on those pre-filled values.

    If I am right then do this:

    $(document).ready(function() {
      if (($("#renewal_boat_fees").val() >= 15) || ($("#new_boat_fees").val() >= 15))
        var result = $("#totalFee").val() - 15;
      $("#final_dues").val(result);
    });
    

    Working snippet:

    $(document).ready(function() {
      if (($("#renewal_boat_fees").val() >= 15) || ($("#new_boat_fees").val() >= 15))
        var result = $("#totalFee").val() - 15;
      $("#final_dues").val(result);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    renewal_boat_fees: <input type="text" id="renewal_boat_fees" value="15"><br>
    new_boat_fees : <input type="text" id="new_boat_fees" value="10"><br>
    totalFee: <input type="text" id="totalFee" value="25"><br>
    final_dues: <input type="text" id="final_dues"><br>