0

I wanted to create a calculator to calculate an Area of a circle, but i think it neither gets a Radius input and also doesnt put the calculated result in input field.

Below is my JavaScript and HTML code:

function calculateAreaOfCirle(myRadious){
    return myRadious * myRadious * Math.PI;
}
const Radious = document.getElementById("Radious").value;
document.getElementById('Area')[0].value = calculateAreaOfCirle();
calculateAreaOfCirle();
<form>
    <label for="Radious">Radious*Radious</label>
    <input type="text" id="Radious" name="Radious">
    <label for="Pi">*Pi=</label>
    <input type="text" id="Area" name="Area" placeholder="Area">
    <button onclick="calculateAreaOfCirle(myRadious)">Calculate</button>
</form>
  • 1
    Use linters like [JSHint](//jshint.com) to find problems with your code immediately. Relevant linter warnings include that `myRadious` isn’t defined anywhere, `Radious` isn’t used anywhere, `calculateAreaOfCirle` is called without arguments, etc. Inline event handlers like `onclick` are [bad practice](/q/11737873/4642212). They’re an [obsolete, cumbersome, and unintuitive](/a/43459991/4642212) way to listen for events. Always [use `addEventListener`](//developer.mozilla.org/en/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these) instead. – Sebastian Simon Nov 14 '22 at 15:00
  • 1
    You are treating `document.getElementById("Area")` as if it returns a collection of some sort, when it actually simply returns the element. No need for an index. – mykaf Nov 14 '22 at 15:29

1 Answers1

0

The issue you have is that you need to get the current radius value in your function, and when you get the value, it is a String, not a Number. You can either use parseInt or make your input type=number

function calculateAreaOfCirle(){
    const myRadious = parseFloat(document.getElementById("Radious").value);
    document.getElementById('Area').value = myRadious * myRadious * Math.PI;
    
}
//calculateAreaOfCirle();
<form>
    <label for="Radious">Radious*Radious</label>
    <input type="number" id="Radious" name="Radious">
    <label for="Pi">*Pi=</label>
    <input type="text" id="Area" name="Area" placeholder="Area">
    <button type="button" onclick="calculateAreaOfCirle()">Calculate</button>
</form>
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • 1
    The value being a string doesn’t matter if it’s multiplied. Please use `parseInt` [_with_ the second parameter, `10`](/q/16880327/4642212). Consider using [`Number`](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number#Function_syntax) or [`parseFloat`](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseFloat) instead, or, specifically for ``s, [`.valueAsNumber`](//developer.mozilla.org/en/docs/Web/API/HTMLInputElement#Properties). – Sebastian Simon Nov 14 '22 at 15:01