Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a div that returns an array string:

<div class="overview"><%=getCurrentAttribute('item','item_specs_json','""')%></div>

An array string that looks like this:

[{"k":"type","v":"blue"},{"k":"size","v":"large"}]

I am making a bulleted list from these and there are 25 instances of div.overview per page.
This works but only repeats the first item values for every div. I can't get this to loop each.
Is it possible to do this with what I have?

$(function () {
    var specs = $.parseJSON($(".overview").html());
    $("div.overview").html('<div class="bullet_spec"></div>');
    $.each(specs, function () {
        $('div.overview div').append('<ul class="specs"><li class="label">' + this.k + ' : ' + this.v + '</li></ul>');
    });
});

I've tried:

$('.overview').each(function () {

and this breaks the script.
Also FYI, when the script breaks the unique values appear on items correctly in the full array string format.

share|improve this question
1  
It works, jsfiddle.net/LsAXD/1 –  undefined Jan 13 at 21:41

2 Answers 2

up vote 2 down vote accepted

If you've got more than one "overview" element, then you'll have to iterate through that list.

$('.overview').each(function() {
  var $overview = $(this), specs = $.parseJSON($overview.html());
  $overview.html('<div class="bullet_spec"></div>');
  $.each(specs, function () {
    $overview.children('div').append('<ul class="specs"><li class="label">' + this.k + ' : ' + this.v + '</li></ul>');
  });
});
share|improve this answer
    
Thank you, that did it! –  SteveAustin Jan 13 at 22:34

I'm taking 'I am making a bulleted list from these and there are 25 instances per page' to mean there are 25 .overview, each with there own JSON. You can loop through each, mapping each JSON string to a collection of elements, appending the collection at the end:

$('.overview').each(function(){
   var theJSON = JSON.parse(this.innerHTML);
   $elems = $.map(theJSON, function(k,v){
     return $('<ul class="specs"><li class="label">' + k.k + ' : ' + k.v + '</li></ul>');
   });
   $spec = $('<div class="bullet_spec"></div>').append($elems);
   $(this).html($spec);
});

JSFiddle

share|improve this answer
    
---------Thanks! –  SteveAustin Jan 13 at 22:34

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.