Javascript – Best Way to Insert An Element With JavaScript

htmljavascriptjquery

I have an HTML form which consists of several fieldsets (each has identical fields). I want users to be able to add additional fieldsets by clicking a button (jQuery). I can think of two approaches:

  1. Create a dummy hidden fieldset and clone it when the add button is clicked.

  2. Create a function that renders the fieldset's HTML from a string when the add button is clicked. (The function knows the fieldset as a long string.)

Are there any significant advantages or disadvantages to either appoach? Is there another way?

I don't love the idea of a dummy fieldset hanging around, even if it's hidden, but encoding the whole fieldset as a string seems a little unweildy, though I know it's pretty standard practice.

Best Answer

If even the fieldsets that are already present are identical to the one you'd like to insert, you can clone an existing fieldset and clear the inputs. Now you don't have to have the extra code in the HTML or Javascript :)