Creating a dynamic html form

I would like to create a form that changes dynamically.

I have a form for creating a project (with fields such as: project_name, project_description ...), and the project can have any amount (greater than or equal to 0) of categories.

I want to display a button that will give the user the opportunity to add another category field. In addition, I would also like the option for category fields to be β€œdeleted” by the user (if he changes his mind or makes a mistake). What would be the best way to do this. I would like to use a solution like Ajax.

My solution so far is to leave an empty div under the last category and by clicking a button load another field into that div with another div to be used for the next div. Not happy with this decision, since now I have to calculate how many fields I have and give each div its own identifier, which further complicates this issue.

Is there a simpler solution?

+8
source share
3 answers

If you are trying to add fields dynamically using a button, you can easily do this by following these steps:

HTML:

<form> <p> <label>Name:</label> <input type="text"> <label>Age:</label> <input type="text"> <span class="remove">Remove</span> </p> <p> <span class="add">Add fields</span> </p> </form> 

JS:

 $(".add").click(function() { $("form > p:first-child").clone(true).insertBefore("form > p:last-child"); return false; }); $(".remove").click(function() { $(this).parent().remove(); }); 

Demo: http://jsfiddle.net/UeSsu/1/

+12
source

I started writing a form generator based on a definition in JSON some time ago. It works, but can use some improvements. It is written using Prototype.js, but it would not be a huge effort to pass it to jQuery.

You can steal the code . (just view the source)

0
source

I did something like that. To delete the fields, I really did not delete the fields. I just hid them with display:none and had a hidden input "delete" which I call for true. Then the page that receives the result knows which field should be deleted in the database.

They are not deleted until the form is submitted. This is similar to the two-pass concept. But if you really don't need a true ajax, it works great. Otherwise, you will need the JS delete function to call the server and report to remove the field with its identifier. Slightly more complex code.

0
source

All Articles