0

Because of jQuery, I've been able to indulge my laziness to the max, but the real benefit has been spending most time on the good stuff and less on the tedious. I'd like to further that.

Currently, I'll have some HTML like so:

<div id="id1"></div>
<div id="id2"></div>
<div...

and so on.

Then, I'll call ajax, expecting the object "ids" to be the same as the div ids like so:

$.ajax({
    success: function (msg) {
        $("#id1").text(msg.id1);
        $("#id2").text(msg.id2);
        $("#...

and so on.

Can this be reduced to a "one-liner"? Specifically, I don't know how to use the ids of the divs in the response object array.

Many thanks in advance!

2 Answers2

2

If there's someway to separate your div's from other divs on your page you can do it like this

$('div[id^=id]').text(function(){ return msg[this.id]  }); // <-- one liner just for you

Accessing properties of object can be done two ways..

msg.property
msg[property] // <-- this way is more flexible...

So your actually passing in each div's id as the property name

msg[id1] // etc..
wirey00
  • 33,517
  • 7
  • 54
  • 65
1

Yes, it can, use the jQuery.each() method:

success: function (msg) {
  jQuery.each(msg, function(key, value){
    $('#' + key).text(value);
  });
}
Brian Ball
  • 12,268
  • 3
  • 40
  • 51