0

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.

1

2 Answers 2

2

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

Comments

2

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

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.