Using JQuery:
var num = 1;
var clone = $('.form-modelo').clone();
clone.attr('class', 'form-real');
clone.children().each( function() {
$(this).attr('id', $(this).attr('id').replace( /__prefix__/, num ) );
});
$('#form-container').append(clone);
Note: I made some changes when cloning. As it was, you were generating a .form-real
within a copy of the% div .form-modelo
, I believe that is not the desired result.
How you are in your original code:
<div class='form-modelo'>
<input id="id_form-__prefix__-nome" name="form-__prefix__-nome" type="text">
<input id="id_form-__prefix__-texto" name="form-__prefix__-texto" type="text">
</div>
<div class='form-real'>
<div class='form-modelo'>
<input id="id_form-__prefix__-nome" name="form-__prefix__-nome" type="text">
<input id="id_form-__prefix__-texto" name="form-__prefix__-texto" type="text">
</div>
</div>
With the modifications we have a container:
<div class='form-modelo'>
<input id="id_form-__prefix__-nome" name="form-__prefix__-nome" type="text">
<input id="id_form-__prefix__-texto" name="form-__prefix__-texto" type="text">
</div>
<div id='form-container'>
<div class='form-real'>
<input id="id_form-1-nome" name="form-1-nome" type="text">
<input id="id_form-1-texto" name="form-1-texto" type="text">
</div>
</div>
Changes:
- added
clone.attr('class', 'form-real');
to dynamically rename the div;
- used
$('.form-real:last').append(clone);
to add to the end of existing ones, if you want multiple numbered inputs;
- set a
#form-container
to insert the forms, if you want to use more than one.
Demo:
var num;
for( num = 1; num <= 5; num++ ) {
var clone = $('.form-modelo').clone();
clone.attr('class', 'form-real');
clone.children().each( function() {
$(this).attr('id', $(this).attr('id').replace( /__prefix__/, num ) );
});
$('#form-container').append(clone);
}
#id_form-__prefix__-nome {border:2px solid blue;}
#id_form-1-nome {border:2px solid red;}
#id_form-2-nome {border:2px solid cyan;}
#id_form-3-nome {border:2px solid green;}
#id_form-4-nome {border:2px solid orange;}
#id_form-5-nome {border:2px solid magenta;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass='form-modelo'><inputid="id_form-__prefix__-nome" name="form-__prefix__-nome" type="text">
<input id="id_form-__prefix__-texto" name="form-__prefix__-texto" type="text">
</div>
<div id='form-container'></div>