如何使用JS / jQuery将输入字段相互求和

时间:2017-10-30 16:50:48

标签: javascript jquery html input calculator

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

现在我正在尝试对每个输入字段求和。但我在控制台中得到 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>

6 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

收集物品时请勿使用val()

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

但在提取值时使用val()

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

答案 2 :(得分:0)

您正在尝试从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来计算浮点数。

答案 3 :(得分:0)

您可以在此处使用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>

答案 4 :(得分:0)

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

&#13;
&#13;
$(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;
  });

});
&#13;
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);
}
&#13;
<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>
&#13;
&#13;
&#13;

编辑(在香草)

仅供比较,这是没有任何jQuery的功能。

参考

&#13;
&#13;
(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);
})();
&#13;
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);
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 5 :(得分:0)

您要做的是使用类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()来转换数字中的字符串

您还应该检查.input-time元素是否为字符串,以避免出现异常行为。