javascript循环遍历字段,添加值并显示在另一个字段上

时间:2015-07-16 11:39:06

标签: javascript

我有以下代码循环遍历许多字段,其ID前缀和后缀相同,请参阅下面的代码。 我试图添加所有相关字段的总值并将其显示在文本框Id txtTOTAL20,txtTOTAL40和txtTOTAL50上。 这就是我到目前为止(不起作用)

for (var i = 1; i < 14; i++) {
    x = i + 1
    var field1 = "txtF" + i + "_1"; 
    var field2 = "txtF" + i + "_2"; 
    var field3 = "txtF" + i + "_3"
    FIELD20 = FIELD20 + parseInt(field1.value);
    FIELD40 = FIELD40 + parseInt(field2.value);
    FIELD50 = FIELD50 + parseInt(field3.value);
    var text = document.getElementById('txtTOTAL20');text.value = FIELD20;
    var text = document.getElementById('txtTOTAL40');text.value = FIELD40;
    var text = document.getElementById('txtTOTAL50');text.value = FIELD50;
}

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

这应该有效:

//init
var FIELD20 = 0;
var FIELD40 = 0;
var FIELD50 = 0;

for (var i = 1; i < 14; i++) {
    //get values
    var field1 = document.getElementById("txtF" + i + "_1"); 
    var field2 = document.getElementById("txtF" + i + "_2"); 
    var field3 = document.getElementById("txtF" + i + "_3");

    //increment
    FIELD20 += parseInt(field1.value);
    FIELD40 += parseInt(field2.value);
    FIELD50 += parseInt(field3.value);
}

//display totals
document.getElementById('txtTOTAL20').value = FIELD20;
document.getElementById('txtTOTAL40').value = FIELD40;
document.getElementById('txtTOTAL50').value = FIELD50;

答案 1 :(得分:0)

您最想做的事情是通过“数据绑定”来完成的。在这里查看这个基本示例:

var input = document.querySelector('#a');
var output = document.querySelector('p');

function update(event) {
   output.innerHTML = input.value;
}
input.addEventListener('keydown', update);
input.addEventListener('keyup', update);

我们会监听按键和按键事件,然后更改我们的值。 Fiddle for fun.

如果你有一个大表,这可能是笨拙的,因为我们必须将每个输入绑定到它的输出。 ES6不是这样!相反,我们仍然将侦听器添加到输入中,但我们将它们全部绑定到单个JS对象。这是一个事件听众,而不是其他几十个。我们通过Object.observe完成此操作。

检查出来:

var input = document.querySelectorAll('input');
var output = document.querySelectorAll('td');

input = Array.prototype.slice.call(input);

/*
Here you model out your "table" as a JS object
so that we can listen for changes more easily.
*/
var table = {
    a: '',
    b: ''
};

input.forEach(function addListeners(input) {
    //Closured! 
    function update(event) {
        table[input.id] = input.value
    }
    input.addEventListener('keydown', update);
    input.addEventListener('keyup', update);
});

//You'd have to make some more clever function.
function alphaToCell(alpha) {
    if (alpha === 'a') return 0;
    if (alpha === 'b') return 1;
}

/*
The cool thing here is that instead of binding each input to it's output, we just bind every input to a single model, and then that model knows how to update all the outputs.
*/
Object.observe(table, function (changes) {
    changes.forEach(function (change) {
        var index = alphaToCell(change.name);
        output[index].innerHTML = table[change.name];
    })
});

Fiddle for Fun.