我想将两个输入字段的计算输出到第三个,同时输入(keyup,我认为?)。以下只是一个视觉示例,因为我不知道如何做得更好:
<input type="text" class="form-control text-center" id="n1"
maxlength="2" placeholder="1-20">
<input type="text" class="form-control text-center" id="n2"
maxlength="2" placeholder="1-20">
<input type="text" class="form-control text-center" id="sum-out"
maxlength="2" readonly>
$(document).ready(function() {
var n1 = $("#n1").val();
var n2 = $("#n2").val();
var sum = ((n1 + n2) / 10) * 2;
sum = document.getElementById('sum-out')
return sum;
});
请帮忙......
答案 0 :(得分:0)
当某些内容“触发”时,您需要执行计算,而不是在页面准备好后立即执行,因为用户还没有机会输入任何数据。添加一个允许用户告诉程序他们已准备好进行计算的按钮是最简单的事情。
顺便说一句,你的计算实际上并没有得到两个输入的“和”。您可能需要重新考虑变量和元素名称。
$(document).ready(function() {
// You can't calculate the answer as soon as the page is ready.
// You need to wait until the user has done something that triggers
// the calculation. Here, it will happen as the user types into either
// of the first two inputs
$("#n1, #n2").on("input", calc);
// And also when the button is clicked
$("#calc").on("click", calc)
function calc(){
var n1 = $("#n1").val();
var n2 = $("#n2").val();
$('#result').val(((n1 + n2) / 10) * 2);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control text-center" id="n1"
maxlength="2" placeholder="1-20">
<input type="text" class="form-control text-center" id="n2"
maxlength="2" placeholder="1-20">
<input type="text" class="form-control text-center" id="result"
maxlength="2" readonly>
<button type="button" id="calc">Calculate</button>
答案 1 :(得分:0)
如果你没有parseFloat()
这些值,他们会添加为字符串,即使你输入的内容确实是一个数字,例如:((5 + 5) / 10) * 2
将等于11
,而不是2
。 (除非11
是您的预期行为)
$(document).ready(function() {
$("#n1").keyup(function(){
var val = $(this).val();
var other = $('#n2').val();
if($.isNumeric(val) && $.isNumeric(other)){
$('sum-out').val((parseFloat(other) + parseFloat(val)) / 10 * 2)
}
});
$("#n2").keyup(function(){
var val=$(this).val();
var other = $('#n1').val();
if($.isNumeric(val) && $.isNumeric(other)){
$('#sum-out').val((parseFloat(other) + parseFloat(val)) / 10 * 2)
}
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control text-center" id="n1"
maxlength="2" placeholder="1-20">
<input type="text" class="form-control text-center" id="n2"
maxlength="2" placeholder="1-20">
<input type="text" class="form-control text-center" id="sum-out"
maxlength="2" readonly>
&#13;