0

How can I create a dynamic form using jQuery. For example if I have to repeat a block of html for 3 times and show them one by one and also how can I fetch the value of this dynamic form value.

<div>
    <div>Name: <input type="text" id="name"></div>
    <div>Address: <input type="text" id="address"></div>
</div>
1
  • 3
    I believe you should know jQuery before starting to use it in your project. Like there are append appendTo insertBefore insertAfter methods which may help you adding elements dynamically to your webpage. Commented May 31, 2010 at 13:43

2 Answers 2

4

To insert that HTML into a form 3 times, you could simply perform it in a loop.

HTML:

<form id="myForm"></form>

jQuery:

$(function() {
    var $form = $('#myForm');  // Grab a reference to the form

        // Append your HTML, updating the ID attributes to keep HTML valid
    for(var i = 1; i <= 3; i++) {
        $form.append('<div><div>Name: <input type="text" id="name' + i + '"></div><div>Address: <input type="text" id="address' + i + '"></div></div>')
    }
});

As far as fetching values, how you go about it would depend on your intent. jQuery can serialize the entire form, or you can select individual input values.

.append() - http://api.jquery.com/append/

Sign up to request clarification or add additional context in comments.

Comments

1

This is a pretty broad question and feels a lot like 'do my work' as opposed to 'help me solve this problem.' That being said, a generic question begets an generic answer.

You can add new address rows by using the append() method and bind that to either the current row's blur - although that seems messy, or a set of +/- buttons that allow you to add and remove rows from your form. If you're processing the form with PHP on the server side, you can name the fields like this:

<input type='text' name='address[]' />

and php will create an array in $_POST['address'] containing all the values.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.