Vee Vee - 1 month ago 9
HTML Question

Simple Javascript I don't know how to put the functions in the if-else statements

Hi please help me my code is almost complete but it only triggers the last button which is the square root option. It's supposed to look like a calculator which opens up a pop-up button with a text box where you can input your numbers. I cannot trigger the right operation.

<input type="button" value="Add" onclick="calculate('addition')">
<input type="button" value="Subtract" onclick="calculate('subtraction')">
<input type="button" value="Multiply" onclick="calculate('multiplication')">
<input type="button" value="Divide" onclick="calculate('division')">
<input type="button" value="Modulo" onclick="calculate('modulo')">
<input type="button" value="Pow" onclick="calculate('pow')">
<input type="button" value="Factorial" onclick="calculate('factorial')">
<input type="button" value="Sqrt" onclick="calculate('sqrt')">


<script>
function calculate(addition) {
var x= prompt("What is your first number?", "");
var y= prompt("What is your second number?", "");
var z= parseInt(x)+parseInt(y);
document.getElementById("z").value = z;
}
function calculate(subtraction) {
var x= prompt("What is your first number?", "");
var y= prompt("What is your second number?", "");
var z= parseInt(x)-parseInt(y);
document.getElementById("z").value = z;
}

function calculate(multiplication) {
var x= prompt("What is your first number?", "");
var y= prompt("What is your second number?", "");
var z= parseInt(x)*parseInt(y)
document.getElementById("z").value = z;
}

function calculate(division) {
var x= prompt("What is your first number?", "");
var y= prompt("What is your second number?", "");
var z= parseInt(x)/parseInt(y)
document.getElementById("z").value = z;
}
function calculate(modulo) {
var x= prompt("What is your first number?", "");
var y= prompt("What is your second number?", "");
var z= parseInt(x)%parseInt(y)
document.getElementById("z").value = z;
}

function calculate(pow) {
var x= prompt("What is your first number?", "");
var y= prompt("Raised to?", "");
var i=1
while (i<(parseInt(y)+1)) {
var z= parseInt(x)*parseInt(x)
i=parseInt(i)+1
}
document.getElementById("z").value = z;
}
function calculate(factorial) {
var x= prompt("What is your number?", "");
var i=1
var m=1
while (m<(parseInt(x))) {
i=parseInt(i)*((parseInt(m)+1))
m=parseInt(m)+1
}
document.getElementById("z").value = i;
}
function calculate(sqrt) {
var x= prompt("What is your number?", "");
i=1
while (i%parseInt(x)!=0) {
z=(parseInt(x)%i)
i=parseInt(i)+1
}
z=Math.sqrt(parseInt(x))
document.getElementById("z").value = z;
}


</script>




Answer

There is no function overloading in JS based on parameter passed. You can write the calculate function once and handle different cases in it.

function calculate(op) {
  if (op == 'addition')//do addition
  else if (op == 'subtraction')//do subtraction
  ...
}