2

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?

AB Siddik
  • 337
  • 5
  • 18

3 Answers3

4

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);
hsz
  • 148,279
  • 62
  • 259
  • 315
2

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])

Ullas Hunka
  • 2,119
  • 1
  • 15
  • 28
0

Use html(totalCharge) instead of append(totalCharge)

Kavin Wong
  • 11
  • 1