jquery calculation question
I have this code:
<div>
&l开发者_开发问答t;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.
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"
<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
<option value="minus">
<option value="plus">
if the .val()
of the element is 'minus' then do x, if its plus do y, etc.
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).
精彩评论