[Solved] Dynamically add an input to an HTML form [closed]


I’m struggling whether to vote to close this as a duplicate, even though it’s not exact. But what you’re looking for appears to be answered here. The main difference is that where they are binding to the change event for a select element:

$("#selectBox").change(function() {

you would instead bind to the click event of an anchor element (your “Add” link):

$("#addLink").click(function() {

The “Delete” link would work in a similar manner. As the HTML is created for the new input, you’d also create the “Delete” link to go next to it before adding it to the DOM (the call to the .html() function in the referenced code). You’ll want to make sure that you give the added HTML a unique id (wrapped in a div with a unique id for example), as well as to the added “Delete” link.

Then, after it’s added to the DOM, you’d add an event handler to the “Delete” link:

$("#deleteLink123").click(function() {

In this handler you’d reference the unique id of the container of what was added to the DOM and remove it. I’m sure there’s a more elegant way to handle this by using the .live() function here and some more clever selectors. It would be interesting to re-factor something like this while trying to not be too clever so as to hurt ongoing support.

There are some additional considerations you’ll want to keep in mind as you develop this:

  1. The anchor tags are by default links, but it looks like you don’t want them to link to anything. You can link them to “#” but that’s not really elegant. You could remove the href attribute from them entirely, but then you’ll also need to style them to visually behave like links. Not difficult, but not intuitive either. Why not buttons?
  2. How the actual form behaves when handled by the server is up to you. You can dynamically add elements to the DOM to your heart’s content, but that may not help you on the server-side. That’s another question entirely, though.

3

solved Dynamically add an input to an HTML form [closed]