遍历对象数组以填充输入字段

Iterating through Array of Objects to fill input fields

本文关键字:输入 字段 填充 对象 数组 遍历      更新时间:2023-09-26

我目前正在为谷歌表单制定一个解决方案,该解决方案将能够将所有输入存储在cookie中,以便用户可以在不同的时间进行调查。目前,我可以存储所有问题(Question是一个对象,它包含:周围div的id,required,通过使用JSON.stringify()在cookie中进行用户输入。我还可以读取和解析cookie,从而获得所有问题对象的数组。

现在我想填充所有字段或检查所有有值的单选按钮。我的问题是,内部for循环只进行2次迭代,但应该进行18次。你知道可能出了什么问题吗?

function restoreInputs() {
    // number of stored cookies
    var countCookies = 27;
    console.log(countCookies);
    // iterate through all cookies
    for (var i = 1; i < countCookies + 1; i++) {
        var cookiename = "answerswer" + i;
        // get content of cookie (is array of objects)
        var answer = checkCookie(cookiename);
        // iterate through content      
        for (var j = 0; j < answer.length; j++) {
            // get value of object
            var val = answer[j].value;
            // get the input field (textarea or radio button)
            var x = document.getElementById(answer[j].n).getElementsByTagName('input');
            // if input is radio, then check the one at position stored in value of object
            if (x[j].type === "radio") {
                x[val].checked = true;
                // if textarea set its value to the one stored in object value
            } else {
                x[j].value = val;
            }
            console.log("j: " + j);
        }
    }
    console.log(i);
}

我找到了解决方案。问题是我忘记了for循环,因为var x = document.getElementById(answer[j].n).getElementsByTagName('input');可能返回多个元素。因此,解决方案如下:

function restoreInputs() {
// number of stored cookies
var countCookies = 27;
console.log(countCookies);
// iterate through all cookies
for (var i = 1; i < countCookies + 1; i++) {
    var cookiename = "answerswer" + i;
    // get content of cookie (is array of objects)
    var answer = checkCookie(cookiename);
    // iterate through content      
    for (var j = 0; j < answer.length; j++) {
        // get value of object
        var val = answer[j].value;
        // get the input field (textarea or radio button)
        var x = document.getElementById(answer[j].n).getElementsByTagName('input');
        // if input is radio, then check the one at position stored in value of object
        for (var k = 0; k < x.length; k++) {
            if (x[k].type === "radio") {
                x[val].checked = true;
                // if textarea set its value to the one stored in object value
            } else {
                x[k].value = val;
            }
        }
        console.log("j: " + j);
    }
}
console.log(i);

}