Question

I've been working on a very simple calculator in JavaScript. Basically, you input two values, choose your method of calculation, and then hit go and it spews out a value. Here's a JSfiddle I made showing the concept:

http://jsfiddle.net/JHeqN/

The odd thing is, in my browser it does run the calculations, but only addition, no matter what I select. In JSfiddle, it does not even run the calculations. I think the problem might be with my If,ElseIf statement, but I'm not sure where or why. What I have at the moment is this:

function calculateTotal() {
var value1 = document.getElementsByName('value1')[0].value;
var value2 = document.getElementsByName('value2')[0].value;
var calcMethod = document.getElementsByName('calculationType')[0].value;
var out;

if (calcMethod = 'add')
    {
    out = parseFloat(value1) + parseFloat(value2);
    }
else if (calcMethod = 'subtract')
    {
    out = parsefloat(value1) - parsefloat(value2);
    }
else if (calcMethod = 'multiply')
    {
    out = parsefloat(value1) * parsefloat(value2);
    }
else if (calcMethod = 'divide')
    {
    out = parsefloat(value1) / parsefloat(value2);
    }

document.getElementsByName('total')[0].value= out;

}

What this does is it takes the names assigned by the select value in my HTML, here:

<select name="calculationType">
    <option value="add">+</option>
    <option value="subtract">-</option>
    <option value="multiply">*</option>
    <option value="divide">/</option>
</select><br>

And assigns the value to the variable calcMethod. It then checks which of these values was selected in order to determine which type of math to calculate. I've checked this using the console in Chrome, and the value is properly assigned. when I select division, calcMethod does equal 'divide' at runtime, but it still adds, or does nothing in the case of JSfiddle.

Was it helpful?

Solution

Use === and not =

The === is a comparision and the = is an assignment.

Forget that == exists.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top