I've got a very simple javascript calculator here but it doesn't seem to be working. I'm sure it's something very simple to solve but just can't see it. I've spent a while on it and thought I'd be better off asking here. Any suggestions? Thanks! /
Width <input type="Text" name="width" size="4">
Height <input type="Text" name="height" size="4" onkeyup=""> <br><br>
Area <input type="Text" name="area" id="area" size="4"> <br><br>
<input type="button" name="calculate" id="area" size="4" onclick="calculateArea()" value="calculate">
And here's the javascript:
function calculateArea() {
var width = document.getElementById("width").value;
var height = document.getElementById("height").value;
var area = width * height;
document.getElementById("area").value = area;
}
I've got a very simple javascript calculator here but it doesn't seem to be working. I'm sure it's something very simple to solve but just can't see it. I've spent a while on it and thought I'd be better off asking here. Any suggestions? Thanks! http://jsfiddle/z98gb/7/
Width <input type="Text" name="width" size="4">
Height <input type="Text" name="height" size="4" onkeyup=""> <br><br>
Area <input type="Text" name="area" id="area" size="4"> <br><br>
<input type="button" name="calculate" id="area" size="4" onclick="calculateArea()" value="calculate">
And here's the javascript:
function calculateArea() {
var width = document.getElementById("width").value;
var height = document.getElementById("height").value;
var area = width * height;
document.getElementById("area").value = area;
}
Share Improve this question asked Nov 17, 2011 at 20:31 LarsLars 8,50812 gold badges54 silver badges70 bronze badges3 Answers
Reset to default 2You didn't specify an id for your input
Working example : http://jsfiddle/z98gb/8/
You need to convert your DOM values to actual numbers before performing calculations on them. Use parseInt
if you're working with whole numbers, or, more likely, use parseFloat
to support decimals.
If you use parseInt
, don't forget to specify a 10 to signify base 10. Failure to do so will cause JavaScript to treat leading zeroes as though they were in base 8.
var width = parseInt(document.getElementById("width").value, 10);
var height = parseInt(document.getElementById("height").value, 10);
var area = width * height;
EDIT
Also, as Francis notes, you forgot to add IDs to your inputs.
You're using getElementById and not getElementByName. You either need to specify an id or switch what you use in your code.