【问题标题】:How to sum input fields with each other using JS/jQuery如何使用 JS/jQuery 将输入字段相互求和
【发布时间】:2018-04-11 17:41:08
【问题描述】:

我正在尝试制作一个带有输入元素的小型计算器。我已经构建了一个加号按钮,用于在最后一个输入字段之后插入一个新的输入字段。它正在工作。

现在我正在尝试对每个输入字段求和。但我在控制台中得到 undefined 。我不知道出了什么问题,因为我是编程新手。 我尝试使用 .input-time 类获取输入字段的值,然后将其放入数组中。然后做一个 for 循环来对它们求和。

编辑:

非常感谢您的帮助。我使用了@Yoiki 的代码,因为它是一种新的、简单的方法。我编辑了剪断的代码。它现在正在工作。

$(function() {
  
  // ADDING NEW INPUT FIELD
  $('.button-plus').on('click', function(event) {
    event.preventDefault();
    
    let inPut = $('.input-time');
    let inPutArr = jQuery.makeArray( inPut );
    // console.log(inPutArr);

    let lastInPut = inPutArr[inPutArr.length-1]; // get last elem of array
    $(lastInPut).addClass('lastone'); // add class to it
    $('.lastone').after('<input type=\"text\" class=\"input-time\">');
    $('.lastone').delay(10).removeClass('lastone');
  });
  
  /* OLD CODE - NOT WORKING!!!
  $('#button-calc').on('click', function(event) {
    event.preventDefault();
    let inPutV = $('.input-time').val();
    let inPutVal = jQuery.makeArray( inPutV );
    for (var i = 0; i < inPutVal.length; i++) {
      var sum = sum + inPutVal[i];
    }
    console.log(sum);
  });
  */
  
  // NEW CODE - WORKING!!!
  $('#button-calc').on('click', function(event) {
    event.preventDefault();

    let sum = 0;

    $('.input-time').each (function () {
      sum += +$(this).val();
    });
    console.log (sum);
  });
});
/* IGNORE THE STYLE ;) */

input {
  width: 160px;
  height: 20px;
  padding: 10px 20px 10px 20px;
  border: none;
  border-radius: 20px;
  font-size: 15px;
  display: block;
  margin-bottom: 10px;
}

.container {
  background-color: #dde4fe;
  padding: 20px;
  width: 200px;
  margin-right: 20px;
  margin-left: auto;
  margin-right: auto;
  margin-top: 100px;
}

.button-plus {
  width: 40px;
  height: 40px;
  background-color: #9aadfd;
  color: #fff;
  cursor: pointer;
  margin-top: 10px;
  margin-left: auto;
  margin-right: auto;
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}


#button-calc {
  width: 200px;
  height: 40px;
  background-color: #5677fc;
  color: #fff;
  cursor: pointer;
  margin-top: 20px;
  margin-bottom: 0;
}

.btn-plus {
  width: 20px;
  margin-left: auto;
  margin-right: auto;
  height: 5px;
  background-color: #5677fc;
  border-radius: 5px;
  position: absolute;
}

.plus-1 {
  transition: 0.5s;
  transform: rotate(0deg);
}

.plus-2 {
  transition: 0.5s;
  transform: rotate(90deg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<section class="container">
  <div class="container-inner">
    <input type="text" class="input-time">
    <input type="text" class="input-time">
    <div class="button-plus">
      <div class="btn-plus plus-1"></div>
      <div class="btn-plus plus-2"></div>
    </div>
    <input type="submit" id="button-calc" value="Calculate">
  </div>
</section>

【问题讨论】:

    标签: javascript jquery html input calculator


    【解决方案1】:

    sum 未定义,因此当您向其添加一个数字时,您就是将该数字添加到 undefined。你需要先设置sum = 0

    关于帮助避免意外使用未定义值的建议,请尝试在代码开头包含 'use strict' - 它会强制您定义变量等。

    【讨论】:

      【解决方案2】:

      在收集对象时不要使用val()

      inPutV = $('.input-time');

      但是在提取值时使用val()

      sum = sum + inPutVal[i].val()

      【讨论】:

        【解决方案3】:

        您想要做的是使用类input-time 迭代所有元素并获取每个元素的值。您不能直接获取值数组。

        $('#button-calc').on('click', function(event) {
           event.preventDefault();
        
           let sum = 0; // Init the variable outside the loop
        
           $('.input-time').each (function () { // This is how you iterate all .input-time element
            sum += +$(this).val(); // And then you get the value
           });
           console.log (sum);
        });
        

        $(this).val() 返回输入的文本,但它是一个字符串,您需要一个数字 才能添加到sum。这就是为什么我在$(this).val() 之前使用+ 来转换number 中的string

        您还应该检查.input-time 元素是否为字符串以避免奇怪的行为。

        【讨论】:

          【解决方案4】:

          您正在尝试从您的 jQuery 选择中分配返回的元素。您需要遍历元素并从每个元素中提取对象。我没有在这里做 isNaN 或任何错误检查,但这有效。

          $('#button-calc').on('click', function(event) {
            event.preventDefault();
            var total = 0;
            $.each( $('input.input-time'), function(idx, elm) {
              var v = $(elm).val()
              total += parseFloat(v);
            });
          
            console.log(total);
          
          });
          

          我还使用 parseFloat 来计算浮点数。

          【讨论】:

            【解决方案5】:

            您可以在此处使用 map/reduce 操作来简化您的代码。 您可以 map() 他们只返回值,然后 reduce() 这个值数组加上一个加法,而不是循环输入。

            $(function() {
              
              // ADDING NEW INPUT FIELD
              $('.button-plus').on('click', function(event) {
                event.preventDefault();
                
                let inPut = $('.input-time');
                let inPutArr = jQuery.makeArray( inPut );
                // console.log(inPutArr);
            
                let lastInPut = inPutArr[inPutArr.length-1]; // get last elem of array
                $(lastInPut).addClass('lastone'); // add class to it
                $('.lastone').after('<input type=\"text\" class=\"input-time\">');
                $('.lastone').delay(10).removeClass('lastone');
              });
            
              // DOING CALCULATION - WORKING NOW
              $('#button-calc').on('click', function(event) {
                event.preventDefault();
                var sum = $('.container-inner input[type=text]').map(function(index, ob) {
                	return parseInt(ob.value);
                }).get().reduce(function(a, b) {
                  return a + b;
                });
                console.log(sum);
              });
            
            });
            /* IGNORE THE STYLE ;) */
            
            input {
              width: 160px;
              height: 20px;
              padding: 10px 20px 10px 20px;
              border: none;
              border-radius: 20px;
              font-size: 15px;
              display: block;
              margin-bottom: 10px;
            }
            
            .container {
              background-color: #dde4fe;
              padding: 20px;
              width: 200px;
              margin-right: 20px;
              margin-left: auto;
              margin-right: auto;
              margin-top: 100px;
            }
            
            .button-plus {
              width: 40px;
              height: 40px;
              background-color: #9aadfd;
              color: #fff;
              cursor: pointer;
              margin-top: 10px;
              margin-left: auto;
              margin-right: auto;
              border-radius: 20px;
              display: flex;
              align-items: center;
              justify-content: center;
            }
            
            
            #button-calc {
              width: 200px;
              height: 40px;
              background-color: #5677fc;
              color: #fff;
              cursor: pointer;
              margin-top: 20px;
              margin-bottom: 0;
            }
            
            .btn-plus {
              width: 20px;
              margin-left: auto;
              margin-right: auto;
              height: 5px;
              background-color: #5677fc;
              border-radius: 5px;
              position: absolute;
            }
            
            .plus-1 {
              transition: 0.5s;
              transform: rotate(0deg);
            }
            
            .plus-2 {
              transition: 0.5s;
              transform: rotate(90deg);
            }
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
            <section class="container">
              <div class="container-inner">
                <input type="text" class="input-time">
                <input type="text" class="input-time">
                <div class="button-plus">
                  <div class="btn-plus plus-1"></div>
                  <div class="btn-plus plus-2"></div>
                </div>
                <input type="submit" id="button-calc" value="Calculate">
              </div>
            </section>

            【讨论】:

            • 感谢您提供另一种方式。 :) 我以前从未使用过 reduce。
            【解决方案6】:

            您的第一个问题是变量范围,在您尝试记录它时 sum 不存在,在我的示例中,我在任何其他函数之外定义 sum,以便它对您的 IIFE 是块级全局的。第二个问题是在您的计算回调中,您的 inPutV 变量正在拉取选择器的值,要对其进行迭代和求和,您需要拉取选择器,然后对其进行迭代以获得总和。第三个问题,您的输入是文本类型,而不是数字,因此需要将它们转换为数字才能成功添加(您也可以更改输入类型,这是我的建议)。

            $(function() {
              let sum = 0
              
              // ADDING NEW INPUT FIELD
              $('.button-plus').on('click', function(event) {
                event.preventDefault();
                
                let inPut = $('.input-time');
                let inPutArr = jQuery.makeArray( inPut );
                // console.log(inPutArr);
            
                let lastInPut = inPutArr[inPutArr.length-1]; // get last elem of array
                $(lastInPut).addClass('lastone'); // add class to it
                $('.lastone').after('<input type=\"text\" class=\"input-time\">');
                $('.lastone').delay(10).removeClass('lastone');
                
                sum = 0;
              });
            
              // DOING CALCULATION - NOT WORKING
              $('#button-calc').on('click', function(event) {
                event.preventDefault();
                let inPutV = $('.input-time');
                let inPutVal = jQuery.makeArray( inPutV );
                for (var i = 0; i < inPutVal.length; i++) {
                  sum += Number(inPutVal[i].value);
                }
                console.log(sum);
                
                sum = 0;
              });
            
            });
            input {
              width: 160px;
              height: 20px;
              padding: 10px 20px 10px 20px;
              border: none;
              border-radius: 20px;
              font-size: 15px;
              display: block;
              margin-bottom: 10px;
            }
            
            .container {
              background-color: #dde4fe;
              padding: 20px;
              width: 200px;
              margin-right: 20px;
              margin-left: auto;
              margin-right: auto;
              margin-top: 100px;
            }
            
            .button-plus {
              width: 40px;
              height: 40px;
              background-color: #9aadfd;
              color: #fff;
              cursor: pointer;
              margin-top: 10px;
              margin-left: auto;
              margin-right: auto;
              border-radius: 20px;
              display: flex;
              align-items: center;
              justify-content: center;
            }
            
            
            #button-calc {
              width: 200px;
              height: 40px;
              background-color: #5677fc;
              color: #fff;
              cursor: pointer;
              margin-top: 20px;
              margin-bottom: 0;
            }
            
            .btn-plus {
              width: 20px;
              margin-left: auto;
              margin-right: auto;
              height: 5px;
              background-color: #5677fc;
              border-radius: 5px;
              position: absolute;
            }
            
            .plus-1 {
              transition: 0.5s;
              transform: rotate(0deg);
            }
            
            .plus-2 {
              transition: 0.5s;
              transform: rotate(90deg);
            }
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
            
            <section class="container">
              <div class="container-inner">
                <input type="text" class="input-time">
                <input type="text" class="input-time">
                <div class="button-plus">
                  <div class="btn-plus plus-1"></div>
                  <div class="btn-plus plus-2"></div>
                </div>
                <input type="submit" id="button-calc" value="Calculate">
              </div>
            </section>

            编辑(原版)

            只是为了比较,这里是你没有任何 jQuery 的功能。

            参考

            (function() {
              // Create object to store sum and number of inputs on page
              const data = { sum: 0, inputs: 2, };
            
              // Event handler for creating new inputs
              const addInput = e => {
                e.preventDefault();
                // create a new input element (eg: $('<input/>');)
                const newInput = document.createElement('input')
                // assign input type, and class to new element
                newInput.type = 'number';
                newInput.classList.add('input-time');
            
                // get input container (eg: $('.container-inner');)
                const container = document.querySelector('.container-inner')
                // this inserts the new input before the end of the element
                container.insertBefore(newInput, container.children[data.inputs]);
            
                // update number of inputs, to allow adding more.
                data.inputs += 1;
              };
            
              // Event handler for getting sum of inputs
              const sumInputs = e => {
                e.preventDefault();
                // get all elements of class input-time (eg: $('.input-time');)
                const inputs = document.querySelectorAll('.input-time');
                data.sum = Object.keys(inputs)                // keys for inputs object in array form
                  .filter(key => !isNaN(key))                 // filter out non-numbers
                  .map(val => parseInt(inputs[val].value)) .  // map new array from input values
                  .reduce((sum, current) => sum + current, 0);// sum array of input values
                console.log(data.sum);
              };
            
              // get your add button and sum button (eg: $('.button-plus');)
              const buttonAdd = document.querySelector('.button-plus');
              const buttonSum = document.querySelector('#button-calc');
            
              // create event listeners (eg: $('.button-plus').on('click', addInput);)
              buttonAdd.addEventListener('click', addInput, false);
              buttonSum.addEventListener('click', sumInputs, false);
            })();
            input {
              width: 160px;
              height: 20px;
              padding: 10px 20px 10px 20px;
              border: none;
              border-radius: 20px;
              font-size: 15px;
              display: block;
              margin-bottom: 10px;
            }
            
            .container {
              background-color: #dde4fe;
              padding: 20px;
              width: 200px;
              margin-right: 20px;
              margin-left: auto;
              margin-right: auto;
              margin-top: 100px;
            }
            
            .button-plus {
              width: 40px;
              height: 40px;
              background-color: #9aadfd;
              color: #fff;
              cursor: pointer;
              margin-top: 10px;
              margin-left: auto;
              margin-right: auto;
              border-radius: 20px;
              display: flex;
              align-items: center;
              justify-content: center;
            }
            
            
            #button-calc {
              width: 200px;
              height: 40px;
              background-color: #5677fc;
              color: #fff;
              cursor: pointer;
              margin-top: 20px;
              margin-bottom: 0;
            }
            
            .btn-plus {
              width: 20px;
              margin-left: auto;
              margin-right: auto;
              height: 5px;
              background-color: #5677fc;
              border-radius: 5px;
              position: absolute;
            }
            
            .plus-1 {
              transition: 0.5s;
              transform: rotate(0deg);
            }
            
            .plus-2 {
              transition: 0.5s;
              transform: rotate(90deg);
            }
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
            
            <section class="container">
              <div class="container-inner">
                <input type="number" class="input-time">
                <input type="number" class="input-time">
                <div class="button-plus">
                  <div class="btn-plus plus-1"></div>
                  <div class="btn-plus plus-2"></div>
                </div>
                <input type="submit" id="button-calc" value="Calculate">
              </div>
            </section>

            【讨论】:

            • 这很有帮助。谢谢。 :) 如果我将输入类型更改为数字,我会得到那些箭头来更改我不想要的值。也许最好把它改成数字,如果我能禁用它们,我会谷歌它。
            • 因此,经过进一步思考,我认为无论哪种方式,您都必须在此处将输入解析为数字,因为您没有使用表单元素并以这种方式获取表单数据。
            • 是的,最好这样做。顺便说一句,感谢香草代码。看起来很复杂。
            • 没问题,原版肯定更冗长,jQuery 做了很多文档创建元素并在幕后添加事件监听器的东西。 ES6 箭头函数看起来很花哨,但您可以在此上下文中将它们替换为普通函数,而无需大量代码更改。如果您对发生的事情感到好奇,我会仔细阅读并发表评论:)
            猜你喜欢
            • 2020-06-14
            • 1970-01-01
            • 1970-01-01
            • 2021-02-14
            • 2016-03-25
            • 2012-03-03
            • 1970-01-01
            • 2014-08-04
            • 2016-06-20
            相关资源
            最近更新 更多