如何使用JQuery处理输入的选择进行计算并显示结果。
<input type="text" id="num1"/>
<select name="Calc">
<option value="add">ADD</option>
<option value="subtract">SUBTRACT</option>
<option value="multiply">MULTIPLY</option>
<option value="divide">DIVIDE</option>
</select>
<input type="text" id="num2"/>
<button id="Calculate">CALCULATE</button>
<button id="clear">CLEAR</button>
Calculated Value:
<div class="valueDisp">
<div id="calc_value">
</div>
</div>
$('input[name=Calc]').ready(function () {
var selected = $(this).val();
var num1 = $('#num1').val();
var num2 = $('#num2').val();
if (selected == 'add') var total = +num1 + +num2;
else if (selected == 'subtract') var total = num1 - num2;
else if (selected == 'multiply') var total = num1 * num2;
else if (selected == 'divide') var total = num1 / num2;
else var total = ("Please select an option");
$("#calculate").click(function () {});
$("#clear").click(function () {
$('.input').val("");
});
$("#calc_value").html(total);
});
我有以下内容:http://jsfiddle.net/kHtHA/5/
答案 0 :(得分:2)
您可以尝试此操作(检查attribute
的值select
,更改它,但还有其他方法)
<option value="add">ADD</option>
成为
<option value="+">ADD</option> <!--and so on-->
<强> JS:强>
$(document).ready(function () {
$('#Calculate').click(function(){
var operand = $('select[name=Calc]').val();
var num1 = $('#num1').val();
var num2 = $('#num2').val();
if(num1.match(/\d/) && num2.match(/\d/)) {
var total = eval(num1 + operand + num2);
$("#calc_value").html(total);
}
});
});
答案 1 :(得分:1)
检查更新:http://jsfiddle.net/kHtHA/7/
var doCalculate = function () {
var selected = $('select[name="Calc"]:eq(0)').val();
var num1 = $('#num1').val();
var num2 = $('#num2').val();
if (selected == 'add') var total = +num1 + +num2;
else if (selected == 'subtract') var total = num1 - num2;
else if (selected == 'multiply') var total = num1 * num2;
else if (selected == 'divide') var total = num1 / num2;
else var total = ("Please select an option");
$("#calc_value").html(total);
};
$('#Calculate').click(doCalculate);
$('select[name="Calc"]').change(doCalculate);
答案 2 :(得分:1)
不是100%确定你想要什么。小提琴更新:http://jsfiddle.net/kHtHA/14/。
$('#Calculate').on('click', function(e){
var num1 = parseInt($('#num1').val());
var num2 = parseInt($('#num2').val());
if(isNaN(num1) || isNaN(num2)){
return;
}
var operator = $('select[name=Calc]').val();
var total;
switch(operator){
case "add":
total = num1 + num2;
break;
case "subtract":
total = num1 - num2;
break;
case "multiply":
total = num1 * num2;
break;
case "divide":
total = num1 / num2;
break;
}
$('#calc_value').html(total);
});
$('#clear').on('click', function(e){
$('#num1').val("");
$('#num2').val("");
});