Question

How can I add the values of a json object to the span tags of an existing unordered list (in correct sequence)?

Tried this but it's only adding the last value of the object to the span tags:

$.each(case_data['stage'+id+''], function(key, value) {
    $('#stageInfo li').each(function() {
        $(this).find('span').text(value);
    });
});

Object:

 {
  "baseline":{
     "duration":"1 year",
     "age":"45",
     "hba1c":"7.6",
     "fpg":"7.9",
     "bmi":"29",
     "complications":"Overweight Hypertension",
     "baseline":"Metformin"
  },
  "stage1":{
     "duration":"2 years",
     "age":"46",
     "hba1c":"8.1",
     "fpg":"8.3",
     "bmi":"29",
     "complications":"Limited Progression Hypertension",
     "baseline":"Metformin"
  },
  "stage2":{
     "duration":"5 years",
     "age":"49",
     "hba1c":"8.2",
     "fpg":"8.4",
     "bmi":"33",
     "complications":"Patient takes early retirement; daily physical activity reduced",
     "baseline":"Metformin"
  },
  "stage3":{
     "duration":"10 years",
     "age":"55",
     "hba1c":"9.3",
     "fpg":"9.8",
     "bmi":"33",
     "complications":"Diagnosed with retinopathy grade 2",
     "baseline":"Metformin"
  }
}

HTML

        <ul id="stageInfo" class="stage_info">
            <li>1 <span></span></li>
            <li>2 <span></span></li>
            <li>3 <span></span></li>
            <li>4 <span></span></li>
            <li>5 <span></span></li>
            <li>6 <span></span></li>
            <li>7 <span></span></li>
        </ul>
Was it helpful?

Solution

Like that: http://jsfiddle.net/hyUzd/

var ind = 0;
$.each(case_data['stage'+id], function(key, value) {
    $('#stageInfo li').eq(ind++).find('span').text(value);
});

OTHER TIPS

I Would render the li items using the jQuery code.

remove the content from the UL:

<ul id="stageInfo" class="stage_info"></ul>

And build it whitin the loop:

var index = 0;
$.each(case_data['stage'+id+''], function(key, value) {
    index++;
    $("#stageInfo").append("<li>"+index+"<span>"+value+"</span></li>");
});

Good Luck

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top