简体   繁体   English

输入数字字段jquery的倍数总和

[英]Sum value of multiples input number field jquery

i have multiple input number fields with the same class, and i have to sum them but when I try with my javascript i get always NaN result 我有多个具有相同类的输入数字字段,我必须将它们相加,但是当我尝试使用JavaScript时,我总是得到NaN结果

var arrNumber = new Array(); //contain the number of specific input field

        var totale;
        $(".input-n-pro").bind('keyup mouseup', function () {
             totale = 0;
        $('.input-n-pro').each(function(){
        var this_num = $(this).val();
            totale = parseInt(this_num)+parseInt(totale);
        })
        console.log("totale="+totale);
});

The html of input is this, generated by php, one for every row of a table 输入的html是由php生成的,用于表的每一行

<input type="number" name="<?php echo $data["name"];?>" min="0" max="500" placeholder="0" class="form-control input-xs input-n-pro" style="display: inline">

I don't know it won't work, it work with only js withous jquery but i have to get the id of every field to do that and i want to do that for everyone with the same class because they are dinamic fields 我不知道这是行不通的,它只能与具有jquery的js一起使用,但是我必须获取每个字段的ID才能做到这一点,并且我想对同一个类的每个人都这样做,因为它们是动态字段

PS The other part of my work, is to get every name of those fields and store them so i can have an array in js where i have the name of input and his number value, but i don't know how to do because they are dinamic PS我工作的另一部分是获取这些字段的每个名称并存储它们,以便我可以在js中创建一个数组,在其中我具有输入的名称及其数字值,但是我不知道该怎么做,因为它们是动态的

You probably parsing something that is not an integer. 您可能解析的不是整数。 Then the parseInt won't work and returns NaN. 然后parseInt将不起作用并返回NaN。 If you sum a NaN, then it stays a NaN, example: 如果对NaN求和,则它保持NaN,例如:

 // working testcase: const testArray = ['2', '3', '4']; let total = 0; for (value of testArray) { total += parseInt(value); } // returns 9 console.log(total); // your testcase: const testArray2 = ['2', '3', 'notANumber']; let total2 = 0; for (value of testArray2) { total2 += parseInt(value); } // returns NaN since we are adding 2 + 3 + NaN = NaN console.log(total2); 

So the solution is to 'negate' the NaN by treating it as 0: 因此解决方案是通过将NaN视为0来“取反” NaN:

  // solution: const myArray = ['2', '3', 'notANumber', '4']; let total = 0; for (value of myArray) { // treat NaN, undefined or any falsey values as 0. total += parseInt(value) || 0; } // returns 9 console.log(total); 

To integrate this concept in your code, you'll get something like: 要将这个概念集成到您的代码中,您将获得类似以下内容的信息:

 let total = 0; $('.input-n-pro').each(() => { let valueInString = $(this).val(); let actualValue = parseInt(valueInString) || 0; total += actualValue; }); 

bind() has been deprecated => use on bind()已被弃用=>

  arrNumber = [], //contain the number of specific input field totale = 0; doTotale(); // first round $(".input-n-pro").on('keyup mouseup change', doTotale); function doTotale() { totale = 0; arrNumber.length = 0; $('.input-n-pro').each(function() { let name = $(this).attr('name'), val = parseInt($(this).val(),10) || 0; arrNumber.push( {name, val }); totale += val; }) console.clear(); console.log("totale =",totale); console.log("arrNumber =", JSON.stringify(arrNumber) ); } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> AA : <input type="number" name="AA" value="5" class="input-n-pro" /> <br> BB : <input type="number" name="BB" value="3" class="input-n-pro" /> <br> CC : <input type="text" name="CC" value="foo" class="input-n-pro" /> <br> <!-- lets insert one input that contains no number --> DD : <input type="number" name="DD" value="2" class="input-n-pro" /> <br> EE : <input type="number" name="EE" value="11" class="input-n-pro" /> <br> FF : <input type="number" name="FF" class="input-n-pro" /> 

Part 1 and 2 of your question 您的问题的第1部分和第 2部分

The reason you get NaN is most probably that if any of the inputs has no value , asking for that value returns an empty string (form fields always return strings) "" . 获得NaN的原因很可能是,如果任何输入都没有value ,则要求该值返回一个空字符串(表单字段始终返回字符串) "" parseInt("") returns NaN . parseInt("")返回NaN

Using vanilla ECMAScript 6, the solution is a one-liner with the help of Array.prototype.reduce : 使用香草ECMAScript 6,在Array.prototype.reduce的帮助下,该解决方案成为一线解决方案:

const sum = [...document.querySelectorAll('.input-n-pro')].reduce((acc, val) => acc += Number(val.value) || 0, 0);

For your second question, just use Array.prototype.map . 对于第二个问题,只需使用Array.prototype.map Also a one-liner. 也是单线的。

const theArr = [...document.querySelectorAll('.input-n-pro')].map(x => {return { name: x.name, value: parseInt(x.value) || 0 }});

Note: The Array spread operator [...document.querySelectorAll('.input-n-pro')] makes an array from the NodeList document.querySelectorAll returns, so you can use Array methods on the list (like reduce and map). 注意:数组传播运算符[...document.querySelectorAll('.input-n-pro')]NodeList document.querySelectorAll返回数组,因此您可以在列表上使用Array方法(如reduce和map) 。

Example: 例:

 calc.addEventListener('click', () => { const sum = [...document.querySelectorAll('.input-n-pro')].reduce((acc, val) => acc += Number(val.value) || 0, 0); console.log(sum); }) getArr.addEventListener('click', () => { const theArr = [...document.querySelectorAll('.input-n-pro')].map(x => {return { name: x.name, value: parseInt(x.value) || 0 }}); console.log(theArr); }) 
 <input type="number" value="5" class="input-n-pro" name="a" /> <input type="number" value="3" class="input-n-pro" name="b" /> <!-- lets insert one input that contains no number --> <input type="text" value="foo" class="input-n-pro" name="m" /> <input type="number" value="2" class="input-n-pro" name="c" /> <input type="number" value="11" class="input-n-pro" name="d" /> <input type="number" class="input-n-pro" name="e" /> <br /> <button id="calc" type="button">Calculate Sum</button> <button id="getArr" type="button">Get Array of name-value pairs</button> 

if one of inputs value is empty then parseInt returns NAN. 如果输入值之一为空,则parseInt返回NAN。 So you can better do a check using IsNan function. 因此,您可以使用IsNan函数更好地进行检查。 if input is empty than assign 0. For example; 如果输入为空,则分配0。

var x= parseInt($('#abc').val()); var x = parseInt($('#abc')。val()); if (isNaN(x)) x = 0; 如果(isNaN(x))x = 0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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