I have n number of tabs from which to collect data, but the problem is that if in the first we have doc 1, doc 2, and in the second we have doc 3, doc 4 - Then the result when saved is obtained in the first tab doc 1, doc 2 , doc 3, doc 4 and in the second doc 1, doc 2, doc 3, doc 4 how can this be corrected? html:

<div id="eventItems"> <div data-section-name="document" id="20"> <div class="cd__item"><div class="cd__item-name"><span>doc 1</span></div></div> <div class="cd__item"><div class="cd__item-name"><span>doc 2</span></div></div> </div> <div data-section-name="document" id="49"> <div class="cd__item"><div class="cd__item-name"><span>doc 3</span></div></div> <div class="cd__item"><div class="cd__item-name"><span>doc 4</span></div></div> </div> <button>save</button> </div> js: $("button").click(function() { var event = [], objEvent = {}, customDocsEvent = []; $('#eventItems').find("[data-section-name='document']").each(function() { $(this).find(".cd__item").each(function() { var name = $(this).find(".cd__item-name").find("span").text() customDocsEvent.push({ name: name }); }); if (customDocsEvent.length) { $('#eventItems').find("[data-section-name='document']").each(function() { var idSection = $(this).attr("id"); objEvent = { "type" : "document", "id" : idSection, "content" : customDocsEvent }; event.push(objEvent); }); } }); var elements = [ { "section" : "event", "data" : event } ]; elements = JSON.stringify(elements); console.log(elements); }); 
  • .find("span") - ?? - Igor
  • span then I forgot to just write in the example, corrected - Dima Vleskov

1 answer 1

  1. In the code, the same customDocsEvent array in all objEvent .

     $('#eventItems').find("[data-section-name='document']").each(function() { customDocsEvent = []; // !!! ... 
  2. Remove the inner loop by $('#eventItems').find("[data-section-name='document']") - it is not needed.

  • No, it does not work, it also duplicates everything when I did it like in your example - Dima Vleskov
  • @DimaVleskov You inaccurately copied my code to yourself. Try again. - Igor