SitePoint Sponsor

# Thread: Calculator

1. ## Calculator

I can't seem to get the subtraction, multiplication, and division functions to work:

<script>
function getit() {
if (document.former.oper.value == "+") {add()}
else if (document.former.oper.value == "-") {subtract()}
else if (document.former.oper.value == "*") {multiply()}
else if (document.former.oper.value == "/") {divide()}
}

function add() {
var num1 = document.former.num1.value;
var num2 = document.former.num2.value;
document.former.answer.value=parseInt(num1) + parseInt(num2)

}
function subtract() {
var num1 = document.former.num1.value;
var num2 = document.former.num2.value;
document.former.answer.value=((num1) - (num2))

}
function multiply() {
var num1 = document.former.num1.value;
var num2 = document.former.num2.value;
document.former.answer.value=((num1) * (num2))

}
function divide() {
var num1 = document.former.num1.value;
var num2 = document.former.num2.value;
document.former.answer.value=((num1) / (num2))

}

</script>
<form name="former">
<input type="text" name="num1">

<select size="1" name="oper">
<option selected value="+">+</option>
<option>-</option>
<option>*</option>
<option>/</option>
&nbsp;
</select><input type="text" name="num2">
<input type="text" name="answer">
<input type="button" value="submit" onClick="getit()">

</form>

2. It's prolly because you don't have parseInt in those, but you do for addition.

3. I thought parseInt was only needed for addition, because '+' is also used when writing sentences from different forms. Combining them instead of adding.

4. Ahhh, it's because of the way you're accessing the <select>. It should be like this:

var o = document.former.oper;
var oper = o.options[o.selectedIndex].value;

5. I just did it using radio buttons. Much easier.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•