Maddy
Maddy

Reputation: 90

is it possible to pass variable from one innerhtml to another innerhtml

my snippet which am developing has four inner htmls with javascript now my question is can we get all these data from all and add(if integer) them or concatinate(if string) and dispaly in another div tag

<script>
 document.getElementById('one').innerHTML = 10;
</script>    

<script>
 document.getElementById('one').innerHTML = 20;
</script>

<div id="one">    
</div>

<div id="two">    
</div>

<div id="three">
    now here i want the sum of the both one and two
</div>

anyone help me is it possible or not if yes how to do it...

Upvotes: 2

Views: 2506

Answers (4)

Rihards
Rihards

Reputation: 10349

This would set the <div id="three"> innerHTML to sum of <div id="one"> and <div id="two">. If you need to just concatenate (you mention both concatenate and sum in your question, so it's not clear which one you actually need) two innerHTML strings then remove the parseInt(); functions.

<script>
document.getElementById('three').innerHTML = parseInt(document.getElementById('one').innerHTML) + parseInt(document.getElementById('two').innerHTML);
</script>

Upvotes: 0

Sushanth --
Sushanth --

Reputation: 55740

Yes it is possible.. Try this

 var x = document.getElementById('one').innerHTML = 10; 
 var y = document.getElementById('two').innerHTML = 20;
 document.getElementById('three').innerHTML = x + y;    

                        OR   
//Using jQuery
$('#one').html(10);  
$('#two').html(20);   
$('#three').html( parseInt($('#one').text()) +  parseInt($('#two').text()));

Check FIDDLE JAVASCRIPT

Check FIDDLE JQUERY

UPDATED Your Markup should look like this

<script>
 var x = document.getElementById('one').innerHTML = 10;
 var y = document.getElementById('one').innerHTML = 20; 
 document.getElementById('three').innerHTML = x + y;    
</script>   

<div id="one">    
</div>

<div id="two">    
</div>

<div id="three">
    now here i want the sum of the both one and two
</div>  

Upvotes: 1

Chandra Sekhar Walajapet
Chandra Sekhar Walajapet

Reputation: 2554

document.getElementById('one').innerHTML +
document.getElementById('two').innerHTML +
document.getElementById('three').innerHTML +
document.getElementById('four').innerHTML;

does it solve ? what kind of question is this ? but the above will only concatenate, if you want to check if its an integer then you goto write a javascript to check if integer.

Upvotes: 0

Juris Vaiders
Juris Vaiders

Reputation: 635

Try this:

var x = 10;
var y = 20;
document.getElementById('one').innerHTML = x;
document.getElementById('two').innerHTML = y;
document.getElementById('three').innerHTML = x+y;

Fiddle

Upvotes: 0

Related Questions