I'm in a beginner JavaScript class and I feel like I have a pretty good grasp on all the intro material. All of my homework assignments work but they seem longer than they have to be, especially my most recent one. I'm not asking for answers to my homework as it is already complete (you can see the code works below) but I was seeing if anyone can give me some ideas for making my code more efficient.
Please don't provide me with new code and say paste this in as I really would like to think about it and learn. Maybe I haven't learned enough yet, but this looks pretty ugly to me from what I've seen online and I also repeat code... The only thing I'm required to do is build this with an object and there can only be one answer displayed at a time. I can't use jQuery or any other libraries.
var obj = {
num1 : document.getElementById('num1'),
num2 : document.getElementById('num2'),
add : document.getElementById("add"),
sub : document.getElementById("sub"),
mult : document.getElementById("mult"),
div : document.getElementById("div"),
result : document.getElementById("result"),
init : function() {
document.getElementById("calculate").onclick = obj.calc;
},
calc : function() {
var num1 = parseFloat(obj.num1.value);
var num2 = parseFloat(obj.num2.value);
if(isNaN(num1) || isNaN(num2)) {
alert("You must enter a number for First Number and Second Number.");
}
else if (num2 === 0) {
alert("You cannot divide by zero");
}
else {
if (obj.add.checked === true) {
var result = num1 + num2;
}
else if (obj.sub.checked === true) {
var result = num1 - num2;
}
else if (obj.mult.checked === true) {
var result = num1 * num2;
}
else if (obj.div.checked === true) {
var result = num1 / num2;
}
else {
alert("Choose an operator")
}
if (obj.result.firstChild){
var para = document.getElementById("para");
console.log(para);
para.parentNode.removeChild(para);
var p = document.createElement("p");
p.setAttribute("id", "para");
p.appendChild(document.createTextNode("The answer is " + result));
obj.result.appendChild(p);
}
else {
var p = document.createElement("p");
p.setAttribute("id", "para");
p.appendChild(document.createTextNode("The answer is " + result));
obj.result.appendChild(p);
}
}
}
}