I have been stuck on this and don't really know how to go about fixing it myself. I've tried using firebug and getting parts of it to work, but it's just so frustrating and time consuming for such a small script. Perhaps I'm using the switch statement wrong...
Essentially I'm making a very simple calculator using an Object for the first time... Any little bit will help--any push in the right direction :)
Thanks so much for reading!
The HTML file is this:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Homework 8</title>
<link href="css/main.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="calc">
<p><label for="num1">First Number:<input type="text" id="num1" class="txt" /></label></p>
<p><label for="num2">Second Number: <input type="text" id="num2" class="txt"/></label></p>
<p><label for ="add"><input type="radio" name="operation" id="add" value="add"/>Add</label>
<label for ="sub"><input type="radio" name="operation" id="sub" value="sub"/>Subtract</label>
<label for ="mult"><input type="radio" name="operation" id="mult" value="mult"/>Multiply</label>
<label for ="div"><input type="radio" name="operation" id="div" value="div"/>Divide</label></p>
<p><input type="button" id="calculate" value="Do Calculation"/></p>
</div>
<div id="result"></div>
<script type="text/javascript" src="js/hw8.js"></script>
<script type="text/javascript">obj.init();</script>
</body>
</html>
The Javascript file is this short script:
var obj = {
add : document.getElementById("add"),
sub : document.getElementById("sub"),
mult : document.getElementById("mult"),
div : document.getElementById("div"),
num1 : document.getElementById("num1"),
num2 : document.getElementById("num2"),
result : document.getElementById("result"),
calculate : document.getElementById("calculate"),
init : function(){
obj.calculate.onclick = obj.resultArea;
},
resultArea : function(){
var num1Value = parseFloat(num1.value);
var num2Value = parseFloat(num2.value);
if (!isNaN(obj.num1Value) = true || !isNaN(obj.num2Value) = true){
alert("Please enter only numbers in the First Number and Second Number fields!");
return;
}
switch(true){
case obj.add.checked : var ans = (num1Value + num2Value); break;
case obj.sub.checked : var ans = (num1Value - num2Value); break;
case obj.mult.checked : var ans = (num1Value * num2Value); break;
case obj.div.checked && num2Value != 0 : var ans = (num1Value / num2Value); break;
case obj.div.checked && num2Value = 0 : alert("cannot divide by zero"); break;
}
var p = document.createElement("p");
p.appendChild(document.createTextNode("The answer is" + ans));
obj.result.appendChild(p);
},
}
Homework 8, is this a homework question? If so, tag it as such.