Reputation: 29
I found subjects like mine but I couldn't fix my problem after reading them, So I wanted to make a simple calculator using JS but I couldn't do it and it keeps doing nothing ! I think the main problem is with the radio buttons.
Can you help me, it's kind of easy I know but I'm still a beginner. PS: I don't want jquery!!!
<!DOCTYPE html>
<html>
<head>
<title>Exercice1 | JS</title>
<script>
function calcul (op, v1, v2){
if (document.f.op[1].cheked) alert(parseInt(v1.value) + parseInt(v2.value));
if (document.f.op[2].cheked) alert(parseInt(v1.value) - parseInt(v2.value));
if (document.f.op[3].cheked) alert(parseInt(v1.value) * parseInt(v2.value));
if (document.f.op[4].cheked) alert(parseInt(v1.value) / parseInt(v2.value));
}
</script>
</head>
<body>
<form name ="f" method="POST" action="">
<label for="v1">Var 1</label>
<input type="text" name="v1" id="v1"></input>
<br> <br>
<label for="v2">Var 2</label>
<input type="text" name="v2" id="v2"></input>
<br><br>
<input type="radio" name="op" value="1"></input>
<label for="1">+</label>
<br>
<input type="radio" name="op" value="2"></input>
<label for="2">-</label>
<br>
<input type="radio" name="op" value="3"></input>
<label for="3">*</label>
<br>
<input type="radio" name="op" value="4"></input>
<label for="4">/</label>
<br>
<input type="submit" onclick="calcul(op, v1, v2)" value="Calculate"></input>
<input type="reset"></input>
</form>
</body>
Upvotes: 0
Views: 1572
Reputation: 160
Few things that could fix off my head:
Do not pass op, v1, v2 in your calcul function, and change your function to function calcul () because you've used those three - (op, v1, v2) to declare your elements' name's anyways - variables with the same names are accessible in your function anyways
cheked is incorrect, it's .checked
function calcul (){
if (document.f.op[0].checked) alert(parseInt(v1.value) + parseInt(v2.value));
// you are accessing an array - so index starts with Zero
if (document.f.op[1].checked) alert(parseInt(v1.value) - parseInt(v2.value));
if (document.f.op[2].checked) alert(parseInt(v1.value) * parseInt(v2.value));
if (document.f.op[3].checked) alert(parseInt(v1.value) / parseInt(v2.value));
}
Change this too:
onclick="calcul()"
Upvotes: 1