G.D
G.D

Reputation: 181

How to get number from a div on button click?

I am adding two numbers and the sum is placed in a hidden div. I have a button and when i click on it I want to get that number from div. how can I do that? thx!

my code:

$(document).ready(function () {
            var _nmr1 = document.getElementById("txtNmr1").value = Math.floor((Math.random() * 10) + 1);
            var _nmr2 = document.getElementById("txtNmr2").value = Math.floor((Math.random() * 10) + 1);

            var nmr1 = parseInt(_nmr1);
            var nmr2 = parseInt(_nmr2);
            var sum = nmr1 + nmr2;

            document.getElementById("hiddenSum").innerText = sum;

        });

        function checkAnswer() {

             var getDiv = document.getElementById("hiddenSum");
            document.write(getDiv); //returns: [object HTMLDivElement]
        }

<div id="hiddenSum" style="display:none;"></div>

Upvotes: 0

Views: 204

Answers (1)

Shailendra Sharma
Shailendra Sharma

Reputation: 6992

you are missing innerText write document.write(getDiv.innerText) to read text from that div that's why [object HTMLDivElement] is returning, because getDiv is a dom object of that div and you just need innerText property of that. i hope will this make sense for you :)

function checkAnswer() {

     var getDiv = document.getElementById("hiddenSum");
    document.write(getDiv.innerText); //this will return text inside div: 
}

Upvotes: 1

Related Questions