您在输入字段id="thousands"
中输入的值将乘以1000,结果将显示在输入字段id="thousands-output"
中。代码的这一部分工作得很好。我想要的是获得所有乘法输出的值的总和,并将其显示在输入字段id="totalBills"
中。我似乎无法解决这个问题。任何帮助将不胜感激
HTML代码:
<label>1000</label>
<div class="input-group">
<input type="number" class="form-control" name="thousands" id="thousands" />
<span class="input-group-addon">=</span>
<input type="text" class="form-control txt" id="thousands-output" style="width:70%;" readonly />
</div>
<label>500</label>
<div class="input-group">
<input type="number" class="form-control" name="five_hundreds" id="five_hundreds"/>
<span class="input-group-addon">=</span>
<input type="text" class="form-control txt" id="five_hundreds-output" style="width:70%;" readonly />
</div>
<input type="total" id="totalBills" class="form-control" value="0">
Javascript代码:
var $output = $("#thousands-output");
$("#thousands").keyup(function() {
var value = parseFloat($(this).val());
$output.val(value*1000);
});
var $output2 = $("#five_hundreds-output");
$("#five_hundreds").keyup(function() {
var value = parseFloat($(this).val());
$output2.val(value*500);
});
答案 0 :(得分:1)
使用querySelectorAll
和reduce
//all the outputs are the child of input-group and has type="text"
var allOutputs = document.querySelectorAll( ".input-group input[type='text'].txt" );
//iterate all the output values. If the value is a number, add to the accumulator, else add 0
var sum = [ ...allOutputs ].reduce( ( a, c ) => a + ( isNaN( c.value ) ? 0 : +c.value ) , 0);
//now display this value
document.getElementById( "totalBills" ).value = sum;
答案 1 :(得分:1)
您需要获取这两个值并添加它并将其设置为输入字段的值。
function getSum(){
var sum = +$("#thousands-output").val() + +$("#five_hundreds-output").val();
$("#totalBills").val(sum);
}
在keyup
事件
var $output = $("#thousands-output");
$("#thousands").keyup(function() {
var value = parseFloat($(this).val());
$output.val(value * 1000);
getSum();
});
var $output2 = $("#five_hundreds-output");
$("#five_hundreds").keyup(function() {
var value = parseFloat($(this).val());
$output2.val(value * 500);
getSum();
});
function getSum(){
var sum = +$("#thousands-output").val() + +$("#five_hundreds-output").val();
$("#totalBills").val(sum);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>1000</label>
<div class="input-group">
<input type="number" class="form-control" name="thousands" id="thousands" />
<span class="input-group-addon">=</span>
<input type="text" class="form-control txt" id="thousands-output" style="width:70%;" readonly />
</div>
<label>500</label>
<div class="input-group">
<input type="number" class="form-control" name="five_hundreds" id="five_hundreds" />
<span class="input-group-addon">=</span>
<input type="text" class="form-control txt" id="five_hundreds-output" style="width:70%;" readonly />
</div>
<input type="total" id="totalBills" class="form-control" value="0">
&#13;
<强>更新强>
使用unary
运算符+
将字符串转换为数字。
答案 2 :(得分:0)