[英]Jquery loop through only those inputs which has values in it
I am trying to loop through form fields and add the value of each input and show the total in another div. 我试图遍历表单字段并添加每个输入的值,并在另一个div中显示总计。 It is working for me only if I fill all the form fields. 仅当我填写所有表单字段时,它才对我有用。 How I can make it work if I have values only in my 2 form fields? 如果仅在2个表单字段中有值,如何使它起作用?
HTML: HTML:
<ul class="nav tabs " id="calculate">
<li class="active"><input type="text" class="col-sm-3 pull-right" id="right-input"></li>
<li><a href="#tab2" data-toggle="tab"> <input type="text" class="col-sm-3 pull-right" id="right-input"></a></li>
<li><a href="#tab3" data-toggle="tab"><input type="text" class="col-sm-3 pull-right" id="right-input"></a></li>
<li><a href="#tab4" data-toggle="tab"><input type="text" class="col-sm-3 pull-right" id="right-input"></a></li>
<li><a href="#tab5" data-toggle="tab"><input type="text" class="col-sm-3 pull-right" id="right-input"></a></li>
<li><a href="#tab6" data-toggle="tab"><input type="text" class="col-sm-3 pull-right" id="right-input"></a></li>
<li><a href="#tab7" data-toggle="tab"><input type="text" class="col-sm-3 pull-right" id="right-input"></a></li>
<li><a href="#tab8" data-toggle="tab"><input type="text" class="col-sm-3 pull-right" id="right-input"></a></li>
<li><a href="#tab9" data-toggle="tab"><input type="text" class="col-sm-3 pull-right" id="right-input"></a></li>
<li><a href="#tab10" data-toggle="tab"><input type="text" class="col-sm-3 pull-right" id="right-input"></a></li>
</ul>
JS: JS:
$(document).ready(function()
{
$("input").keyup(function()
{
var $inputs = jQuery('#calculate :input');
var values = {};
var total = 0;
$inputs.each(function()
{
if(values[this.name] !== "")
{
total = parseFloat(total) + parseFloat(values[this.name]);
}
if(total)
});
console.log(total);
});
});
您可以在循环前过滤输入,这将为您提供值不为空的输入。
var $inputs = jQuery('#calculate :input').filter(function(){return this.value !==''});
You have to do little change in you each()
loop like this: 您只需在您的each()
循环中进行一些更改,如下所示:
$inputs.each(function () {
if ($(this).val() !== "") {
total = parseFloat(total) + parseFloat($(this).val());
}
});
You need to change how you add up your values, try this: 您需要更改汇总值的方式,请尝试以下操作:
var value = !isNaN(Number(values[this.name])) ? parseFloat(values[this.name]) : 0;
total += value;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.