1

I'm doing a each function for all elements with a spesific class, but here it only fetches the last one, and not putting all of them into the JSON-array.

JS fiddle here: http://jsfiddle.net/MYGCM/1/

Here is the HTML:

<div id="324834" class="selected_pages">One</div>
<div id="436346" class="selected_pages">Two</div>
<div id="768653" class="selected_pages">Three</div>

Jquery

 var pages = new Object();
 var publish = [];

 $('.selected_pages').each(function () {
 pages.name = $(this).text();
 pages.id = this.id;
 publish.push({
     Pages: pages
 });
 });

 var json_pages = JSON.stringify(publish);

 alert(json_pages)

Any input on this?

Kim
  • 1,128
  • 6
  • 21
  • 41

3 Answers3

3

For each selected_pages you need to create a page object as shown below

var publish = [];

$('.selected_pages').each(function () {
    var pages = new Object();
    pages.name = $(this).text();
    pages.id = this.id;
    publish.push({
        Pages: pages
    });
});

var json_pages = JSON.stringify(publish);

alert(json_pages)

I would recommend using .map() here

var pages = $('.selected_pages').map(function () {
    var page = new Object();
    page.name = $(this).text();
    page.id = this.id;
    return { Pages: page};
}).get();

var json_pages = JSON.stringify(publish);

console.log(json_pages)

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

You can use the map() function to build the array before your stringify it. Try this:

var pages = $('.selected_pages').map(function() {
    var $el = $(this);
    return { Pages: { name: $el.text(), id = this.id } };
}).get();
var json_pages = JSON.stringify(pages);
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

JSFIDDLE: http://jsfiddle.net/MYGCM/3/

You actually want this:

var pages = new Object();
 var publish = [];

 $('.selected_pages').each(function () {
     var page = new Object();
     page.name = $(this).text();
     page.id = this.id;
     publish.push(page);
 });


pages["Pages"] = publish;

 var json_pages = JSON.stringify(pages);

 alert(json_pages)
sajawikio
  • 1,516
  • 7
  • 12