0

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>

0

2 Answers 2

2

.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>

Sign up to request clarification or add additional context in comments.

Comments

2

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.

6 Comments

That may be nit-picking, but "...because text() returns a jQuery object..." is only true for the case when calling .text() with an argument.
Nit-picking is good - it ensures accuracy :) and you're right. I've updated the answer to be more clear.
Are you the OP? I am confused. Also, what's the error?
Who are you? You're not the OP, and I'm not going to amend someone's random answer.
The person who asked the question
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.