javascriptjqueryformsonchangejqueryform

How can get last value of form charge in jQuery


I am trying to make a form where a customer can choose parson and automatically show the cost depend on parson number. So for that, I used jQuery form change function and calculate the cost inside of the function. My all logic is working ok but the issue is when increasing number then showing multiple costs.

Visual look:

enter image description here

Always I want to show the last one/ updated one

Blow my code:

var adultsSingleChage = 200;
var childrenSingleCharge = 100;
var infantsSingleCharge = 50;


$('#absbt_form input').change(function(){
    var adults = $("#absbt_adults").val();
    var adultsCharge = adults * adultsSingleChage;

    var children = $("#absbt_children").val();
    var childrenCharge = children * childrenSingleCharge;

    var infants = $("#absbt_infants").val();
    var infantsCharge = infants * infantsSingleCharge;

    var totalCharge = adultsCharge + childrenCharge + infantsCharge;

    console.log(totalCharge);


    $('.total_cost').append(totalCharge);

});

I know I did the maximum of logic but for last logic, I'm confused.

How can I just show the last one?


Solution

  • append adds new content to existing one - that's the reason of having previous values.

    Instead of using append use text:

    $('.total_cost').text(totalCharge);