Rohit Verma
Rohit Verma

Reputation: 3785

Why i'm getting [object object] using jQuery?

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>

Upvotes: 0

Views: 50

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

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.

Upvotes: 2

Syed mohamed aladeen
Syed mohamed aladeen

Reputation: 6755

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

Upvotes: 2

Related Questions