Welcome to WebmasterWorld Guest from

Forum Moderators: open

Message Too Old, No Replies

Javascript to add fields to form and then some

2:24 pm on Aug 20, 2010 (gmt 0)

5+ Year Member

I am at a complete loss here. I need a form where users can select from a drop down box a certain location and then next to the drop down box is a text field where they can enter information about the location. But, under the text field I want "add another field" option where they can add another field and enter another piece of info for the certain location. Then on top of all of that I want under all of that "add another location".

Location 1------------- text field 1.1
----------------------- text field 1.2
----------------------- [add another field]
Location 2------------- text field 2.1
----------------------- text field 2.2
----------------------- text field 2.3
----------------------- [add another field]
[Add another location]

I hope this makes sense. I've been trying everything I come across on the web but I can't seem to get anything to work. Any help would be appreciated, thank you.
10:41 am on Aug 23, 2010 (gmt 0)

10+ Year Member

That is actually fairly simple.

Create the HTML with a basic section for a location, with a dropdown, a text input and a button to add another text field.

Bind an event to that button, that would append a clone of the text field to that section.

And add a button after the section, that would clone the section and itsert it after the last existing section.

If you go the jQuery way, you could do it fairly quickly.

Don't forget to use the names like name="somename[]" in the HTML inputs, so the form can be processed properly in the backend.
2:03 am on Aug 24, 2010 (gmt 0)

5+ Year Member

What jQuery functions would you use to get this done?
9:21 am on Aug 24, 2010 (gmt 0)

10+ Year Member

A simple working example for a section like this:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
button = $(this);
section = button.parents('.section:first');
titleInput = section.find('input.title:first').clone();
button.before( titleInput.val('') );
button = $(this);
section = $('.section:first').clone();
$(':input',section).each(function(){ this.value = this.defaultValue; });
button.before( section );
<p class='section'>
<select class='location'><option>I'm a dummy!</option><option>I'm a dummy!</option></select>
<input type='text' name='title[]' class='title' />
<button class='add-input'>Add an input</button>
<button class='add-section'>Add a section</button>

As you can see, one of the main jQuery functions in my example are the clone() function, take a look at it in their documentation.

I hope the rest of the code makes sense.

Of course, this is only a sample, it might need a lot of customization to be used in production.

Hope it helps.
12:01 pm on Aug 24, 2010 (gmt 0)

5+ Year Member

Edit: never mind figured it out. Thanks again.