How can get last value of form charge in jQuery

213 views Asked by At

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?

3

There are 3 answers

0
hsz On BEST ANSWER

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);
2
Kavin Wong On

Use html(totalCharge) instead of append(totalCharge)

0
Ullas Hunka On

The problem is with the code you are appending which means you are adding the text into the element instead of replacing it. You can use the following two methods:

  1. text(): $('.total_cost').text("iota")
  2. html(): $('.total_cost').html("iota")

Note: Use id selector or with class use $($('.total_cost')[0])