简体   繁体   中英

How can I create a dynamic form using jQuery

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>

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/

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM