0

I have two < div > section having numbers inside. When number present in 1st < div > is clicked , 2nd content should show twice the value of 1st < div >.

I used following code but not working.

<div id="left"><a href="#" onclick="document.getElementById('right').innerHTML = (parseInt(document.getElementById('left').innerHTML) + parseInt(document.getElementById('left').innerHTML))">1</a></div>

<div id="right">1</div>

But the output is coming as

NaN

Can somebody help with correct code ? Thanks

logan
  • 7,946
  • 36
  • 114
  • 185

1 Answers1

2

The element #left contains the entire anchor, so you're getting all the HTML of the anchor back, and not just the number, which is why parseInt spits out NaN.

In other words:

document.getElementById('left').innerHTML

will return:

<a href="#" onclick="document.getElementById('right').innerHTML = (parseInt(document.getElementById('left').innerHTML) + parseInt(document.getElementById('left').innerHTML))">1</a>

And when parsing that as an integer it returns NaN ?

FIDDLE

You can solve it by doing:

<div id="left"><a href="#" onclick="calc(this); return false;">1</a></div>
<div id="right">1</div>

<script type="text/javascript">
    function calc(elem) {
        var val = parseInt(elem.innerHTML,10) * 2;
        document.getElementById('right').innerHTML = val;
    }
</script>

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388