Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 (bigger or equal to 0) of categories.

What i want is to display a button which would give the user the option to add another category field. In addition I would also like the option for category fields to be "deleteable" by the user (if he changes his mind or made a mistake). What would be the best way to do so. I would like an Ajax type solution.

My solution so far is to leave an empty div beneath the last category and onclick of the button to load another field into that div with yet another div which will be used for the next div. Not to happy with this solution since i now have to count how many fields I have and give each div it's own id which complicates the matter even more.

Is there a more simple solution to this?

like image 739
Nachshon Schwartz Avatar asked Mar 01 '11 15:03

Nachshon Schwartz


People also ask

How do I create a dynamic form in HTML?

The task is to create an HTML form dynamically with the help of JavaScript. There are two approaches that are discussed below. Approach 1: Use document. createElement() to create the new elements and use setAttribute() method to set the attributes of elements.

How do you create a dynamic form?

To create a form dynamically with JavaScript, we can use the document. createElement method to create the element. Then we can use the setAttribute method to set the element attributes. Then we can use the appendChild method to append the elements into the parent element.

What is a dynamic form?

Make real-time changes to your forms based on user input, save customers' progress so they can finish later on any device, and pre-populate data to reduce errors. Dynamic forms also lets you validate fields for proper formatting and automatically verify data like addresses and credit card numbers.

What Builder is used to create dynamic forms?

Make dynamic forms, and share or embed them in your site with Jotform's dynamic form builder — no coding required! Set up conditional logic, data verification, pre-populated form fields, and more in a few easy clicks.


1 Answers

If you are trying to add fields dynamically with a button, you can easily do so by doing something like the following:

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/

like image 136
dmackerman Avatar answered Oct 18 '22 08:10

dmackerman