Toni
Toni

Reputation: 3

jquery calculation question

I have this code:

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

    <select id="Selection" name="D1"> 
    <option>Plus 1</option>
    <option>Minus 1</option>
    </select>

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

How could I calculate any number entered into the input "number" based on the value chosen from the select control using jQuery? For example I would like to enter 5 in the input "number" and if I choose "Plus 1" then add 1 to the number and show the result in the "result" input. If I choose "Minus 1" then I will do a substraction and show the new result. thank you.

Upvotes: 0

Views: 6570

Answers (4)

Scott Evernden
Scott Evernden

Reputation: 39986

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

    <select id="Selection" name="D1"> 
        <option value="1">Plus 1</option>
        <option value="-1">Minus 1</option>
    </select>

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

$('#Selection').change(function() {
   $('#result').val(parseInt($('#number').val(),10) + parseInt($(this).val(),10));
})

EDIT: yep, the comments are correct, and i've edited the code to reflect that

Upvotes: 1

MightyE
MightyE

Reputation: 2679

If you want to support better than just addition and subtraction, you could do it as an eval() if you are careful about how data gets into #number:

<input id="number" />
<select id="Selection">
    <option value="+1">Plus 1</option>
    <option value="-1">Minus 1</option>
    <option value="*2">Times 2</option>
</select>
<input id="result"/>
<input type="button" onclick="$('#result').val(  eval($('#number').val() + $('#Selection').val()); );" value="Calculate" />

Do not let URL or FORM data be supplied as a default value for number though, or else you have opened yourself to a cross-site scripting vulnerability (XSS).

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630627

You can do it like this:

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

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

Give it a try here, the important part is the parseInt() your input (you should also add a numbers-only filter, etc.) Otherwise .val() from either input is a string, think of it this way:

  • 1 + 1 == 2
  • "1" + "1" = "11"

Upvotes: 4

meder omuraliev
meder omuraliev

Reputation: 186762

<option value="minus">
<option value="plus">

if the .val() of the element is 'minus' then do x, if its plus do y, etc.

Upvotes: 0

Related Questions