循环通过JSON对象并使用jQuery动态输出到文本框

时间:2014-01-29 19:42:37

标签: jquery json

我将以下JSON对象返回给我,并希望更新页面上已存在的两个文本框(txtAssigned01和txtAssigned02)的val()。我知道我应该用循环来做这个,但不知道如何在jQuery中动态选择文本框。任何帮助将不胜感激!

JSON对象: enter image description here

到目前为止

代码:

function getAssignedPerson(projectID) {
        $.ajax({
            url: "view-requests.aspx/getAssignedPerson",   // Current Page, Method
            data: JSON.stringify({
                projectID: projectID
            }), // parameter map as JSON
            type: "POST", // data has to be POSTed
            contentType: "application/json", // posting JSON content    
            dataType: "JSON",  // type of data is JSON (must be upper case!)
            timeout: 10000,    // AJAX timeout
            success: function (result) {

                $.each(result, function (i, v) {
                    $('#txtAssigned0'+ v).val(result.d[i]); <--- here's my problem
                });

            },
            error: function (xhr, status) {
                alert(status + " - " + xhr.responseText);
            }
        });
    }

3 个答案:

答案 0 :(得分:1)

如果您想添加新文本框并为其命名,可以使用以下内容:

$('<input>').attr({type: 'text').val("YOUR_VALUE").appendTo('#ID_OF_SOME PARENT_DOM_OBJ')

您还可以通过说例子来添加更多内容,例如on_click处理程序

$('<input>').attr({type: 'text').val("YOUR_VALUE").appendTo('#ID_OF_SOME PARENT_DOM_OBJ').click(function(){alert('hello');});

答案 1 :(得分:1)

这是fiddle

页面上有以下HTML:

<input id='txtAssigned01'/>
<input id='txtAssigned02'/>

您的数据看起来如下:

var result = {d:['test1', 'test2']};

所以你需要循环结果对象中的数组d:

$.each(result.d, function (i, v) {
    console.log(i);
    console.log(v);
    var x = i + 1;
    $('#txtAssigned0'+ x).val(v); //<--- here's my problem
});

您还需要增加基于零的索引,或者将您的命名约定更改为零,以便您可以:

<input id='txtAssigned00'/>
<input id='txtAssigned01'/>

$.each(result.d, function (i, v) {
    $('#txtAssigned0'+ i).val(v); 
});

这是一个updated fiddle

答案 2 :(得分:0)

       $.each(result, function (i, v) {
           $("#main").append("<input type='text' value='"+v+"' id='txtAssigned_"+i+"' ");
        });

其中#main将是一个id为'main'的div,其中将显示文本字段