views:

29

answers:

2

Hi,

I would like to know how to add support for multiplication in this jQuery solution: http://stackoverflow.com/questions/3239760/jquery-calculation-question

It works well for addition and substraction, but how can it support multiplication?

thanks.

You can see the code example here: http://jsfiddle.net/JRcqk/1/

A: 

You would need some changes in the logic, and also use the dreaded eval .. (if you want an agnostic way of handling the calculations)

$('#Selection').change(calc); //update result when changing the number
$("#number").keyup(calc);     //update result when select changes

function calc() {
  $('#result').val( eval( $('#number').val() + $("#Selection").val() ) );
}

and HTML

<div>
    <input id="number" type="text" />

    <select id="Selection" name="D1"> 
    <option value="+1">Plus 1</option>
    <option value="-1">Minus 1</option>
    <option value="*2">double</option>
    <option value="/2">half</option>

    </select>

    <input id="result" type="text" />
</div>
Gaby
A: 

You can try to avoid the eval function if you use a switch statement and go throguh the values. check this: http://stackoverflow.com/questions/1435012/switch-statement-in-jquery-and-list

Also the solution that Meder proposed was good.

@Gaby - your solution will not perform the addition properly. it will just concatenate both numbers unless you use the parseInt().

@Anurag - It is in the interest of everyone to keep place positive. If you don not wish to contribute to a question then keep going. don't just stop and hurl comments that do not contribute to the question. That does not do any good to the community.

Lopez