fcb1900
fcb1900

Reputation: 359

Howto count a variable inside of innerHTML?

How is it possible to count a variable inside of a innerHTML?

JS

var counter = 1;
counter++;
alert(counter);

$(".end").html('Test ' + counter+1 + ' Test');

HTML

<p class="end"></p>

In my JSfiddle example, it works for alert example, but not in the innerHTML element. Why? How is it getting work?

Upvotes: 2

Views: 549

Answers (6)

4b0
4b0

Reputation: 22323

Use parseInt for math calculation other wise its only string concatenation.

var counter = 1;
counter++;
alert(counter);

$(".end").html('Test ' + parseInt(counter+1) + ' Test');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="end"></p>

Upvotes: 0

Arun D
Arun D

Reputation: 464

You have to add brackets to your code JS Fiddle. Like this

$(".end").html('Test ' +( counter + 1 )+ ' Test');

Upvotes: 0

Mohit Jain
Mohit Jain

Reputation: 351

Just use Brackets, and it will work :

var counter = 1;
counter++;
alert(counter);

$(".end").html('Test ' + (counter+1) + ' Test');

Upvotes: 0

Vinod Louis
Vinod Louis

Reputation: 4876

This happens because initially Test + counter this converts counter int 2 to string hence addition happens as string try wrapping those in brackets as (counter + 1)

$(".end").html('Test ' + (counter+1) + ' Test');

Check fiddle

For more info regarding the + operator see this specification

Upvotes: 0

prasanth
prasanth

Reputation: 22500

Is not adding.Just act like string.Add some () .Then it was added .try this $(".end").html('Test ' +(counter + 1) + ' Test');

var counter = 1;
counter++;
alert(counter);

$(".end").html('Test ' +(counter + 1) + ' Test');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="end"></p>

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 121998

Its because you are doing string concatenation.

Current evaluation

'Test ' + counter+1 + ' Test'
'Test 2' +1 + ' Test'
'Test 21' + ' Test'
'Test 21 Test'

You should wrap your calcualtion insde ()

$(".end").html('Test ' + (counter+1) + ' Test');

When you add () that takes higher precedence and calculates first in the expression.

Current evaluation

'Test ' + (counter+1) + ' Test'
'Test ' + 3 + ' Test'
'Test 3' + ' Test'
'Test 3 Test'

Upvotes: 3

Related Questions