简体   繁体   中英

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. 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?

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:

$(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:

$inputs.each(function () {
         if ($(this).val() !== "") {
             total = parseFloat(total) + parseFloat($(this).val());
         }  
     });

FIDDLE DEMO

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM