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
inside a copy of the div .form-modelo
, I believe that is not the desired result.
As it is in its 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>
Amendments:
- 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 several numbered inputs;
- defined a
#form-container
to insert the Forms, if you are going 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>
<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>
As @Bacco well noted, if the intention is to make the content of
.form-modelo
be converted directly into.form-real
, then instead of using$('<div>').append(clone).html();
useclone.html();
.– Miguel Angelo