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

9
  • Wouldn't twice the value be value*2 not value*value ? Commented Jul 14, 2013 at 17:17
  • I am doing value + value ; pls check the code again Commented Jul 14, 2013 at 17:19
  • If parseInt(x) is giving NaN then NaN + y is y + NaN is NaN. Commented Jul 14, 2013 at 17:19
  • @PaulS. So what is the correct function to use there ? Commented Jul 14, 2013 at 17:21
  • @logan I'm saying you're providing the wrong input, not using the wrong function. Commented Jul 14, 2013 at 17:21

1 Answer 1

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

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

3 Comments

You can parse it as an Integer, it just gives you NaN. Also, I'd suggest using .textContent over .innerHTML for this task.
@PaulS. - well, yeah I suppose.
@PaulS. .parseInt(document.getElementById('left').textContent is working fine... Thanks

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.