[英]How to name an input in order to be an array as a Dynamic form and then sum those values?
I have a dynamic form with JavaScript:我有一个带有 JavaScript 的动态表单:
row.insertCell(4).innerHTML= '<input type="text" name="precioUniArr[]" value = "'+precioUnitario+'">'
Is there a way to get the values of all the precioUniArr[]
inputs with JavaScript in order to make a sum and have a total?有没有办法用 JavaScript 获取所有
precioUniArr[]
输入的值,以便求和并得到总数?
You use document.getElementsByName("precioUniArr[]")
.您使用
document.getElementsByName("precioUniArr[]")
。 This returns a NodeList
, which is an array-like object that you can loop over to get all the values.这将返回一个
NodeList
,它是一个类似数组的对象,您可以遍历它以获取所有值。
var inputs = document.getElementsByName("precioUniArr[]");
var total = 0;
for (var i = 0; i < inputs.length; i++) {
var value = parseFloat(inputs[i].value);
if (!isNaN(value)) {
total += value;
}
}
I believe you may be trying Java or C methods to get this information.我相信您可能正在尝试使用 Java 或 C 方法来获取此信息。 JavaScript works a little bit differently, as the input field always, no matter what, returns a string of text.
JavaScript 的工作方式略有不同,因为输入字段始终返回一串文本。
Try giving the array a simple ID of precioUniArr
.尝试为数组提供一个简单的 ID
precioUniArr
。
When you need to grab the data inside, assuming it's a comma-separated list for input, try this code (it grabs the string of input and splits it into an array by each comma):当你需要抓取里面的数据时,假设它是一个逗号分隔的输入列表,试试这个代码(它抓取输入的字符串并通过每个逗号将其拆分成一个数组):
inputArray = document.getElementById('precioUniArr').value.split(',');
This will store an array formed by a comma-separated string as the array inputArray
.这将存储一个由逗号分隔的字符串组成的数组作为数组
inputArray
。 If it's a space-separated list, just replace the comma in the code with a space.如果是空格分隔的列表,只需将代码中的逗号替换为空格即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.