Docxtemplater array only entering last value

1k views Asked by At

Hello I have a form a user fills out with some dynamic fields that the user can add or remove. On completion of this form a word document is being created using docxtemplater. I am creating an array so that I can loop through the multiple items that will be entered into my document though I am only getting the last item entered.

Javascript:

var methods = document.getElementsByName("Method[]");
var attributes = document.getElementsByName("Attribute[]");
var locations = document.getElementsByName("Location[]");
var len = methods.length;
var mdata = []
for (var x = 0; x < len; x++){
    var element = {
        "Method": methods[x].value,
        "Attribute": attributes[x].value,
        "Location": locations[x].value
    };
    mdata.push(element);
} 
console.log(JSON.stringify(mdata));

var docxvar = {
    ShelfLifeExpiry: $("#shelfdrp").val(),
    monograph: "2",
    "testloop":
    [
       mdata
    ]
};

doc.setData(docxvar);

Document Template:

{#testloop} 
{Method} 
{Attribute} 
{Location} 
{/testloop} 

From console:

[{"Method":"3434","Attribute":"434","Location":"434"},{"Method":"4343","Attribute":"3434","Location":"232"},{"Method":"3231","Attribute":"232","Location":"323321"}]

How do I get all of the values from that are in the console into the document?

1

There are 1 answers

0
edi9999 On

Indeed, Here, you were writing :

arr = [...];
doc.setData({
   testloop: [arr],
});

which means that you were passing a two-dimensional array.

Instead, just write :

arr = [...];
doc.setData({
   testloop: arr,
});