var outgoing_count = 0; var incoming_count = 0; function addWire(direction, wire_data) { return function() { if( this != window.window) { this.remove(); } var template = document.getElementById("fragment"); var clone = document.importNode(template.content, true); count = direction == "outgoing" ? ++outgoing_count : ++incoming_count; clone.querySelectorAll("label").forEach( label => label.setAttribute("for", direction + "-" + label.getAttribute("for") + "-" + count)); clone.querySelectorAll(".form-control").forEach( elem => {elem.id = direction + "-" + elem.id + "-" + count; elem.setAttribute("name", direction + "-" + elem.getAttribute("name") + "-" + count); }); clone.getElementById("btn").id = direction + "-btn"; document.getElementById(direction).appendChild(clone); for(var key in wire_data) { if( key == "action" ){ document.getElementById("action").value = wire_data[key]; } else { document.getElementById(direction + "-" + key + "-" + count).value = wire_data[key]; } } document.getElementById(direction + "-btn").addEventListener("click", addWire(direction)); }; } $(function() { for (let w of outgoing_wires) { addWire("outgoing", w)(); } for (let w of incoming_wires) { console.log(w); addWire("incoming", w)(); } if (outgoing_wires.length == 0 && incoming_wires.length == 0) { addWire("outgoing")(); addWire("incoming")(); } })