I have a function there i want to try sum two numbers using variable like given below, but i'm getting [object object] instead of total of sum.
var convenienceCharge = 100; var totalPgCost = 500; var subTotalPgCost = 0; function totalPgCostFunction() { subTotalPgCost += $('.subTotalPgCost').text(convenienceCharge + totalPgCost + 18); alert(subTotalPgCost); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button onclick="totalPgCostFunction();">Click</button>
.text
will return a object. that is why you are seeing [object object]
You need to do it like this.
var convenienceCharge = 100; var totalPgCost = 500; var subTotalPgCost = 0; function totalPgCostFunction() { subTotalPgCost += convenienceCharge + totalPgCost + 18; $('.subTotalPgCost').text(subTotalPgCost); alert(subTotalPgCost); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button onclick="totalPgCostFunction();">Click</button> <div class="subTotalPgCost"></div>
The issue is because when you call the setter of text()
it returns a jQuery object, hence the output you see.
To make this work you need to split the calculation and text()
logic, like this:
var convenienceCharge = 100; var totalPgCost = 500; var subTotalPgCost = 0; $(function() { $('button').click(function() { subTotalPgCost += convenienceCharge + totalPgCost + 18; $('.subTotalPgCost').text(subTotalPgCost); }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button>Click</button> <div class="subTotalPgCost"></div>
Also note the use of an unobtrusive event handler in this example instead of the outdated on*
attribute.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.