NetizenKing NetizenKing - 5 months ago 19
jQuery Question

Concatenate Ajax success function result set with a Dynamic Column Name

I have a form with several form inputs with the following definition:

<input type="text" name="aname" id="aname" class="form-control dataaccess" data-field="GID" />
<input type="text" name="sname" id="sname" class="form-control dataaccess" data-field="LID" />


Then i have an ajax function whose success function returns a resultset from the controller to display in the page. This is my code

$.ajax({
type: "POST",
url: "controller/method",
data: "id="+data,
success: function(data){
$(".dataaccess").each(function(){
var field=data[0].($(this).data("field"));
$("#"+$(this).attr("id")).val(field);
});

});


However, my resultset is not getting concatenated with the fieldname i get from the respective input data-field attribute. Where am i getting it wrong? Thank you

Data returned by data:

[{"ID":"GR02","Name":"Admins","Valid":"30","Block":"No ","Descr":"Description"}]

Answer

For dynamic properties, you shouldn't use property accessor(.), you can use as index notation

$.ajax({
    type: "POST",
    url: "controller/method",
    data: "id="+data,
    success: function(data){
     $(".dataaccess").each(function(){
         var self = this;  
         var field=data[0][$(self).data("field")];
         $("#"+$(self).attr("id")).val(field);
     });

    });

Define a reference to this as self outside the ajax call, so this can be available when ajax executes.