Ozma64 Ozma64 - 1 month ago 6
HTML Question

Why can't I pull and calculate user form input in Javascript?

I am building a volume calculator for a website, however, I cannot seem to get the user input from the form to pull into Javascript and calculate the volume. It generates no output.



function calculate() {
var x = 0;
var length = parseFloat(document.getElementById("length").value) * 12;
var width = parseFloat(document.getElementById("width").value) * 12;
var depth = parseFloat(document.getElementById("depth").value);
if (document.getElementById("square").checked)
{
x = (length * width * depth) / 12;
}
else if (document.getElementById("circle").checked)
{
x = (Math.PI * length * width * depth / 4) / 12;
}
document.getElementById("result").innerHTML = x;
}

<!DOCTYPE html>
<html>
<body>
<form id="frm1" action="form_action.asp">
<table>
<tr>
<td>
Type:
</td>
<td>
<input type="radio" name="type" value="square" checked> Cubic<br />
<input type="radio" name="type" value="circle"> Cylinder<br />
</td>
</tr>
<tr>
<td>
Length: <br />
(in feet)
</td>
<td>
<input type="text" id="length">
</td>
</tr>
<tr>
<td>
Width: <br />
(in feet)
</td>
<td>
<input type="text" id="width">
</td>
</tr>
<tr>
<td>
Depth: <br />
(in Inches)
</td>
<td>
<input type="text" id="depth">
</td>
</tr>
</table>
</form>
<button onclick="calculate()"><font color="#979189">Calculate</font></button>

<label id="result"> </label> Cubic Feet

<script>
</script>

</body>
</html>





The script should output the calculation into a label but nothing seems to happen. When I attempt to output the data directly to the label from the form field:

document.getElementById("result").innerHTML = document.getElementById("length").value;


It also does not show any output. Would anyone happen to see what I am missing here?

Answer

When you run the code it shows an error in the console that you are trying to access an element with id of square or circle that is not present and these are the radio buttons. You should give them either ids or handle them in some other way: http://www.homeandlearn.co.uk/JS/radio_buttons.html