迭代对象数组以填充输入字段

时间:2015-11-09 15:08:37

标签: javascript arrays for-loop

我目前正致力于Google表单的解决方法,该解决方案能够将所有输入存储在Cookie中,以便用户可以在不同的时间进行调查。 目前我能够存储所有问题(问题是一个对象,包含:使用func setCheckMarkView() { checkMarkView.translatesAutoresizingMaskIntoConstraints = false self.addSubview(checkMarkView) self.addConstraints([ NSLayoutConstraint(item: checkMarkView, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: CGFloat(1), constant: CGFloat(0)), NSLayoutConstraint(item: checkMarkView, attribute: .Trailing, relatedBy: .Equal, toItem: self, attribute: .Trailing, multiplier: CGFloat(1), constant: -UIStyle.Size.standardHorizontalSpacing) ]) } 在cookie中包含的周围div的id,user,userinput。我还能够读取和解析cookie给我一个所有问题对象的数组。

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

JSON.stringify()

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。问题是我忘了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 = "answer" + 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);

}

相关问题