1

I am new to web dev and recently I learning DOM. However, I have a problem that had been bugging me . I am trying out to make a simple sphere volume calculator where the user can get the volume of sphere by inputting the radius.

Here is the code.

HTML

Enter the sphere radius : <input type="number" id="radius"> 
<button id=>Calculate !</button>
<p>Therefore, the volume of sphere are: <span id="volsphere"></span> </p>

JS

var radius = document.querySelector("#radius");
var volsphere = document.querySelector("#volsphere");

volsphere.addEventListener("click",function(){
    //calculate the sphere volume
    var spherevolume = (4/3)  * Math.PI * Math.pow(radius,3);
    //put the text content into sphere volume
    volsphere.textContent = spherevolume ;
});

I try working it out by troubleshooting the console log radius.value and spherevolume.value.

Radius appeared to be fine and giving me "3" but sphere volume have this error message of

VM97:1 Uncaught ReferenceError: spherevolume is not defined at :1:1

So, which part of the code is giving out this error ? Thank you to those who helps

3
  • You've got the click listener on the <span>, you should put it on the button. You're not clicking the span, are you? Commented Jul 13, 2017 at 15:28
  • Your markup looks invalid<button id=>Calculate !</button> You should fill in a value for the button's id attribute or remove the attribute altogether. Commented Jul 13, 2017 at 16:27
  • @Megg My mistake. I should put listener event on the button Commented Jul 31, 2017 at 4:24

1 Answer 1

1

The problem is that you are multiplying the HTMLElement it self and not its value. So add .value after radius, like so:

var spherevolume = (4/3)  * Math.PI * Math.pow(radius.value, 3);

Unfortunately this will return a string and not a number, so to convert it to a number, you could either wrap it in a parseInt() or force it to turn into a number (i.e. subtracting it by 0).

var spherevolume = (4/3)  * Math.PI * Math.pow(parseInt(radius.value), 3);

Or

var spherevolume = (4/3)  * Math.PI * Math.pow(radius.value - 0, 3);

On a side-note, you should probably add the EventListener on the button and not on the span. I'm assuming you did not do that because the whole thing is in a form and thus it was redirecting the page. You can avoid that by adding a event.preventDefault();

var button = document.querySelector("#radius+button");

button.addEventListener("click", function(event){
    var spherevolume = (4/3)  * Math.PI * Math.pow(parseInt(radius.value), 3);
    volsphere.textContent = spherevolume;
    event.preventDefault();
});
Sign up to request clarification or add additional context in comments.

1 Comment

Wouldn't it be worth extracting the value into a variable and doing a parseInt() on it?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.