Search code examples
javascripthtml

Js to duplicate section of fields and rename for form submission


I need to dynamically add fields to a form page so users can add additional entries of the same form. It's a form to describe units in a subdivision, and the number of units and types vary. I need to add like a plus button using js that will allow them to add fields, and for those field names to be incremented I guess so they are all separate inputs into the handler. What i have for html is as follows

<!doctypehtml>
<html lang=en-US>
    <link href=exhibitb.css rel=stylesheet>
    <meta charset=utf-8>
    <title>Chicago Low-Income Housing Trust Fund</title>
    <body>
      <form action=/clihtf.php method=post>
          <div class=bold2>Exhibit B</div>
          <div class=bold>DSU</div>
          <section>
          <p><span>unit:</span><br> <input id=totUni name=totUni type=number>
          <p><label for=nbr><span>nbr:</span></label><br><input id=nbr name=nbr type=number>
          <p><label for=trsu><span>trsu:</span></label><br><input id=trsu name=trsu type=number>
          <p><label for=mtpr><span>Mtpr:</span></label><br><input id=mtpr name=mtpr>
          <p><label for=msasu><span>Monthly SAU:</span></label><br><input id=msasu name=msasu>
          <p><label for=ssfga><span>Social SOP (Exhibit F):<br></span></label><br><input id=ssfga name=ssfga>
          <p><label for=ssfgb>Social Service Plan (Exhibit G):<br><input id=ssfgb name=ssfgb>
          <p><button type=submit value=submit>Submit</button>
      </form>
    </body>

</html>

I have tried what is shown here: Adding input fields in Javascript with onclick button and How to create a minus and plus button to update a field? but I'm just not getting it. I just need to literally duplicate all the fields and then have them be submit with separate names. If this is asking too much, I am sorry.


Solution

  • First of all you have to close the section tag with a /section, for example before the /form.

    Then you can try with something like this :

    var a = $('form section'); // get the section of the form
    var b = $(a[0].innerHTML); // get the components to duplicate
    b.find('[id]').get().forEach(e => $(e).attr('id', $(e).attr('id') + '_1')); // set "ids" of new components
    b.find('[name]').get().forEach(e => $(e).attr('name', $(e).attr('name') + '_1')); // set "names"
    b.find('[for]').get().forEach(e => $(e).attr('for', $(e).attr('for') + '_1')); // set "fors"
    b.find('button').remove(); // do not copy the submit button
    $('form section').append(b); // add new components to the section of the form
    

    Take that example as a basis as it works only for one new bunch of components, you'll have to adapt it for more (or better) implementation.