jquery - Create JSON array by each-loop through parent and child elements -


html:

<section id="intro">         <div id="ih" contenteditable="true">header</div>         <div id="ish" contenteditable="true">subheader</div>         <a id="ibtn" contenteditable="true">test</a> </section>  <section id="articles">         <div id="ah" contenteditable="true">header</div>         <div id="ash" contenteditable="true">subheader</div>         <a id="btn-1" contenteditable="true">button</a>         <a id="btn-2" contenteditable="true">button</a>         <a id="btn-3" contenteditable="true">button</a> </section> 

jquery:

$(document).ready(function() {     $('#edit-button').click(function() {         var dataobj = [];         var jsonobj = [];         $('section').each(function() {             var section = $(this).attr('id');             if( $(this).find('[contenteditable]').length != 0 ) {                 $('[contenteditable=true]').each(function() {                     var id = $(this).attr('id');                     dataobj.push('\"' + id + '\":\"' + $(this).html() + '\"');                 });                 jsonobj.push('{\"' + section + '\":{' + dataobj + '}}');                 dataobj.length = 0;             } else {                 return;             }         });         alert(jsonobj);     }); }); 

goal:

create json array(?) contains section name followed set of elementid+html if of sections children contains attribute contenteditable , attribute set true.

currently it's including it's not ending jsonobj should, includes second section array , second section includes first sections data.

i've tried empty dataobj array using dataobj.length = 0; without success.

what doing wrong?

final goal:

create inline editor connected laravel 5.1 back-end

much rejith's answer, recommend approach:

$(document).ready(function() {     $('#edit-button').click(function() {         var jsonobj = {};         $('section').each(function() {             var section = {};              $(this).find('[contenteditable="true"]').each(function() {                 section[$(this).attr('id')] = $(this).html();             });              jsonobj[$(this).attr('id')] = section;         });         alert(json.stringify(jsonobj));     }); }); 

you don't need build json object form start, can build regular object convert json notation.


Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -