0

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>

2 Answers 2

1

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);
});
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.