循环浏览javascript对象后动态创建文本框

时间:2022-11-29 20:46:57

I have a javascript that sends some info to through an ajax request to the server and receives some data as Questions and their's ID's as a json array.

我有一个javascript,通过ajax请求发送一些信息到服务器,并接收一些数据作为问题,他们的ID作为一个json数组。

This is what the response json array i receive from the server looks like:

这是我从服务器收到的响应json数组看起来像:

   [
     {
      "ID":"1",
      "question":"Write a function called addNum. "
        },
     {
      "ID":"3",
      "question":"Write a function called sumDouble "
      }
    ]

And this is javascript:

这是javascript:

$(document).ready(function(){
    $("form#input_qnumber").submit(function() {

    var questions = $('#questions').attr('value'); // written question
    var quizname = $('#quizname').attr('value');

    if (questions) { // values are not empty
        $.ajax({
            type: "POST",
            url: "https://xxxx",
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            dataType: "application/json",
            data: 'questions='+questions+'&quizname='+quizname,

            success: function (data) 
            {
                var JSONObject = JSON.parse(data); 

                for (var key in JSONObject) {
                    if (JSONObject.hasOwnProperty(key)) {
                        console.log(JSONObject[key]["ID"] + ", " + JSONObject[key]["question"]);
                    }
                }



            }

        });
    }
    else {
        $('div#createquizresp').text("Enter question ID's separated by a comma to be included in the quiz");
        $('div#createquizresp').addClass("error");
    } // else
    $('div#createquizresp').fadeIn();
    return false;
});
});

As you see, I can parse the response json into a javascript object array, loop through it and dump the contents in console. What I would like though would be to create textarea element, give its id attribute the 'ID' key from my array and label it with the corresponding question key from the array. After this I can just append the element to a div inside my html. But I am not really sure how to do it or if its even possible. Please HALP.

如您所见,我可以将响应json解析为javascript对象数组,循环遍历它并将内容转储到控制台中。我想要的是创建textarea元素,从我的数组中给它的id属性'ID'键,并用数组中相应的问题键标记它。在此之后,我可以将元素附加到我的html中的div。但我不确定该怎么做或者它是否可能。请哈尔普。

3 个解决方案

#1


2  

if you want also a label element;

如果你还想要一个标签元素;

for (var key in JSONObject) {
    if (JSONObject.hasOwnProperty(key)) {
        $('<label>')
            .attr('for', JSONObject[key]["ID"])
            .html(JSONObject[key]["question"])
            .appendTo('wherever_you_want');
        $('<textarea>')
            .attr('id', JSONObject[key]["ID"])
            .appendTo('wherever_you_want');
    }
}

#2


0  

create dynamic elements input and label and then append these elements to the parent div or to the body what ever suits your requirement.

创建动态元素输入和标签,然后将这些元素附加到父div或身体以适合您的要求。

DEMO :https://jsfiddle.net/ew4mqhow/3/

<div id ="display"></div>

<script>
var textbox = document.createElement('input');
textbox.setAttribute("id", JSONObject[key]["ID"]);
var labell = document.createElement('label');
labell.setAttribute("for",JSONObject[key]["question"]);
labell.innerHTML = JSONObject[key]["question"];

document.getElementById('display').appendChild(textbox);
document.getElementById('display').appendChild(labell);
</script>

#3


0  

Answer by keune is perfect. One suggestion, tho - do add a prefix to foreign ID's. Just to be on safe side on case You'll assign ID's to other types of elements (ie. answers), too.

通过回答keune是完美的。一个建议是,为外国ID添加前缀。只是为了安全起见,你也可以将ID分配给其他类型的元素(即答案)。

for (var key in JSONObject) {
    if (JSONObject.hasOwnProperty(key)) {
        $('#quizquestions')
            .append($('<label>')
                .attr('for', 'Q' + JSONObject[key]["ID"])
                .html(JSONObject[key]["question"]))
            .append($('<textarea>')
                .attr('id', 'Q' + JSONObject[key]["ID"]))
    }
}

#1


2  

if you want also a label element;

如果你还想要一个标签元素;

for (var key in JSONObject) {
    if (JSONObject.hasOwnProperty(key)) {
        $('<label>')
            .attr('for', JSONObject[key]["ID"])
            .html(JSONObject[key]["question"])
            .appendTo('wherever_you_want');
        $('<textarea>')
            .attr('id', JSONObject[key]["ID"])
            .appendTo('wherever_you_want');
    }
}

#2


0  

create dynamic elements input and label and then append these elements to the parent div or to the body what ever suits your requirement.

创建动态元素输入和标签,然后将这些元素附加到父div或身体以适合您的要求。

DEMO :https://jsfiddle.net/ew4mqhow/3/

<div id ="display"></div>

<script>
var textbox = document.createElement('input');
textbox.setAttribute("id", JSONObject[key]["ID"]);
var labell = document.createElement('label');
labell.setAttribute("for",JSONObject[key]["question"]);
labell.innerHTML = JSONObject[key]["question"];

document.getElementById('display').appendChild(textbox);
document.getElementById('display').appendChild(labell);
</script>

#3


0  

Answer by keune is perfect. One suggestion, tho - do add a prefix to foreign ID's. Just to be on safe side on case You'll assign ID's to other types of elements (ie. answers), too.

通过回答keune是完美的。一个建议是,为外国ID添加前缀。只是为了安全起见,你也可以将ID分配给其他类型的元素(即答案)。

for (var key in JSONObject) {
    if (JSONObject.hasOwnProperty(key)) {
        $('#quizquestions')
            .append($('<label>')
                .attr('for', 'Q' + JSONObject[key]["ID"])
                .html(JSONObject[key]["question"]))
            .append($('<textarea>')
                .attr('id', 'Q' + JSONObject[key]["ID"]))
    }
}