Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

not accepting variable within Jquery .html()

Tags:

jquery

I have the code below that works, but I need to expand it, so I am attempting to make it more streamlined.

success: function setData(data) {
            $("#price" + lastchar).html(data.price);
            $("#matricule" + lastchar).html(data.matricule);
            $("#tag" + lastchar).html(data.tag);
            $("#ins_yr1" + lastchar).html(data.ins_yr1);
            $("#Totalacq" + lastchar).html(data.Totalacq);
        }

Like this:

success: function (data){
  var desc=[];
  desc = ["price","matricule","tag","ins_yr1","Totalacq"];
  for (var i=0;i<desc.length;i++){
    $( "#" + desc[i] + lastchar).html(data.desc[i]);
  }
}

But this does not work because it does not accept a variable desc[i] within the .html(), at least not in the format I am trying to do it.

Any ideas? Thanks!

like image 934
BernardA Avatar asked Dec 29 '25 18:12

BernardA


1 Answers

Your problem is not in html, but in the way you're trying to access data properties. But you can get/set them using [], just like array indices:

data[desc[i]]

In other words, data.price is equivalent to data["price"].

like image 98
mgibsonbr Avatar answered Jan 01 '26 11:01

mgibsonbr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!