我有一个输入列表,将用于设置值(0 到 100)。 这些输入的总值不能超过 100,我已经完成了此操作并且它正在工作,但是如果我更改其中一个输入且总计变为 < 100,我需要一种方法来减去总计。
这是我迄今为止所拥有的一个示例:
var soma_total = 0;
jQuery(function($){
$('input[type=text]').each(function () {
$(this).change(function(){
var valor = $(this).val();
valorPorcentagem = valor;
eE = procPorcentagem(valorPorcentagem);
eE = Math.ceil(eE);
valorPorcentagem = parseInt(valorPorcentagem);
if((parseInt(valorPorcentagem) + soma_total) > 100)
valorPorcentagem = 100 - soma_total;
$(this).val(valorPorcentagem);
soma_total += valorPorcentagem;
console.log(soma_total);
$('#final_sum').append('<li>'+soma_total+'</li>');
});
});
});
function procPorcentagem(entradaUsuario){
var resultadoPorcem = (entradaUsuario * 48) / 100;
return resultadoPorcem;
}
请帮忙,谢谢!
最佳答案
此演示可能会让您了解如何继续:
$(function() {
$(':text').val(0).on('change', function(e) {
var i = $(':text'),
total = 0;
i.each(function() {
total += +this.value;
});
if( total > 100 ) {
this.value -= (total - 100);
}
total = 0;
i.each(function() {
total += +this.value;
});
$('#final_sum').text( total );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text">
<input type="text">
<input type="text">
<div id="final_sum">0</div>
关于javascript - 如果输入因 jquery 更改事件而更改,则重置总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33512255/