0

I' m new to JavaScript and am writing a function which has to calculate circle area. But the problem here is that I don't fully understand the concept of functions. So here is my Html code where i have 2 div elements with specific ID. I want my function to take the innerHTML from the first div and according to the given formula int the function to output the result into the second div. Can you help me cause maybe I make some huge error inhere.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
      <title>Circle Area</title>
      <meta charset="utf-8" />
</head>
<body>
      <div id="area">7</div>
      <div id="output"></div>
      <script type="text/javascript" src="circle-area.js"></script>
</body>
</html>

And here is my Js file

function calcCircleArea(r, formula) {
r = document.getElementById("area").innerHTML;
var formula = Math.PI * (r * r);
return formula;
}
document.getElementById("output").innerHTML = formula;

4 Answers 4

2

You have to call the function

function calcCircleArea() {
    var r       = document.getElementById("area").innerHTML;
    var formula = Math.PI * (r * r);
    return formula;
}

document.getElementById("output").innerHTML = calcCircleArea();

FIDDLE

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

Comments

1

You don't need argument in the function as you are not passing any parameters to the function. You need to call the function. Change your javascript to:

 function calcCircleArea() {
     r = document.getElementById("area").innerHTML;
     var formula = Math.PI * (r * r);
     return formula;
 }
 document.getElementById("output").innerHTML = calcCircleArea();

Comments

1
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Circle Area</title>
    <meta charset="utf-8" />
    <script>
      // There is no need to declare argument variables once again
      // Besides, it's better to get radius from outside, i.e. from function call
      function calcCircleArea(r) {
        return Math.PI * (r * r);
      }
    </script>
  </head>
  <body>
    <div id="area">7</div>
    <div id="output"/>
    <script>
      document.getElementById("output").innerHTML = calcCircleArea(document.getElementById("area").innerHTML);
    </script>
  </body>
</html>

Comments

0
<html>
<body>
<p>This example calls a function which performs a calculation, and returns the result:</p>

<p id="demo"></p>

<script>

function myFunction(a, b) {

    return a * b;

}

document.getElementById("demo").innerHTML = myFunction(4, 3);

</script>

</body>

    enter code here

</html>

This is a simple example for use script inside the html file. It may helps.

Comments

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.