Search code examples
jqueryhtmlclone

Need to iterate through id's in an HTML form and change values


I have a form, which I've simplified for the sake of this forum:

<form id="data0">
    <input id="name0" />
    <input id="address0" />
</form>

Using jQuery I need to clone() this and then change the ids of the cloned form to be name1, address1, etc.

Is there a way to do this without changing them individually like:

$('#data0').children('#name0').attr('id', 'name1');

Like looping through all the inputs and changing '0' to '1.' Thanks.


Solution

  • You would make use of the .clone() api in jQuery to clone the form #data0 first. Then iterate the input element inside the form, replace the id and clear the value, including the form id. After, place the new form to body. So, you should have a counter for incrementing the form id when clicks the add button.

    The following example use data0 form as base for cloning new form.

    HTML

    <input type="button" value="Add form" id="addBtn"/>
    
    <form id="data0">
        <input id="name0" />
        <input id="address0" />
    </form>
    

    JavaScript

    function ReplaceID(element, suffix) {
     var newId = $(element).attr('id').replace(/0/,suffix);
     $(element).attr('id', newId);
     $(element).val(newId); // for demo use, change to '' to reset value
    }
    var formNewId = 1;
    $("#addBtn").on('click', function(){
        var newForm = $("#data0").clone();
        $('input', newForm).each(function(index,element){ // iterate input element inside the form
            ReplaceID(this, formNewId); // replace id
    
        }); 
        ReplaceID(newForm, formNewId); // replace the id of cloned form
        $("body").append(newForm);
        formNewId++;
    });
    

    Working example : http://jsfiddle.net/TfDUE/1/