最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

height - Calculate area from inputs in Javascript - Stack Overflow

programmeradmin7浏览0评论

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 badges
Add a ment  | 

3 Answers 3

Reset to default 2

You 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.

发布评论

评论列表(0)

  1. 暂无评论