Multilevel HTML Form

Imagine, I have an underlying model layout like this (using Play Framework, unrelated):

case class Resume(
                 id: Option[String],
                 surname: String,
                 firstName: String,
                 experience: List[Experience],
                 education: List[Education]
                   )

case class Experience(
                     employer: String,
                     responsibilities: String,
                     position: String,
                     projectDetails: String,
                     projectValue: String
                       )

case class Education(
                    study: String,
                    institution: String
                      )

The resume model is the one the users need to fill in. How would I go about designing the HTML form for it? I need some JS to add a new Experience and Education block on demand if the visitor of my website wants to add an extra Experience or Education block. I want to know, how I can best put this into HTML? Is it better to use html form name arrays or shall I group everything into DIV’s and then using Javascript build a JSON object and submit that to the server?

I’d do it something like this (using the HTML name arrays):

experience[0][employer]
experience[0][responsibilities]
experience[0][position]
experience[0][projectDetails]
experience[0][projectDetails]

… and then when the user presses on tab or something, add:

experience[1][employer]
experience[1][responsibilities]
experience[1][position]
experience[1][projectDetails]
experience[1][projectDetails]

Or is there a better way to tackle this?

Answer

You can use the jQuery method .append(htmlString) to add more items to an existing element.

So if you have a form (with items in it already) then you can have a button that when pressed it will calculate the number of items already added (using .size()) and then append some more inputs.

$('#addNew').click(function() {
  var html = '<div class="experience"><input type="text" id="employer{0}" name="employer" value="emplyer {0}"/></div>';

  var numberAdded = $('.experience').size();

  $('#myForm').append(html.replace(/{0}/g, numberAdded));

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">

  <button id="addNew">Add Experience</button>

</form>

This can be extended with all the inputs you need.

Also you don’t need to bind to a button click, have a look at .keypress() for how to bind the code to when a user presses a button.

Leave a Reply

Your email address will not be published. Required fields are marked *