Вопрос

I'm struggling with the Jquery clone. I can clone a single line of HTML, but I don't have a clue on how to clone a block.

I have this block:

<div class="item-name">
    <label for="id_form-0-name"></label>
    <select id="id_form-0-name" name="form-0-name"></select>
</div>

And I need to produce more two blocks, each time changing the attributes of the new block to reflect its position.

<div class="item-name">
    <label for="id_form-1-name"></label>
    <select id="id_form-1-name" name="form-1-name"></select>
</div>
<div class="item-name">
    <label for="id_form-2-name"></label>
    <select id="id_form-2-name" name="form-2-name"></select>
</div>

Any clue on what I've to do to obtain that output?

Это было полезно?

Решение

Try this:

$('.item-name').clone().insertAfter('.item-name')

Source:

1) About clone() http://api.jquery.com/clone/
2) About insertAfter http://api.jquery.com/insertAfter/

FOR YOUR ADDITIONAL REQUEST

Try something like this:

$clone = $('.item-name:last').clone();
for (i = 1; i < 999; i++) {
    if ($('.item-name select[id=id_form-'+i+'-name]').attr('id') != 'id_form-'+i+'-name') {
        $clone.find('select').attr('id', 'id_form-'+i+'-name');
        $clone.find('select').attr('name', 'form-'+i+'-name');
        $clone.find('label').attr('for', 'id_form-'+i+'-name');
        break;
    }
}
$clone.insertAfter('.item-name:last');

Другие советы

Try this (cloning it twice):

$('.item-name:last').clone().insertAfter($('.item-name:last')).clone().insertAfter($('.item-name:last'));

Working demo

So clone it and increment the attributes. You can do it in one line but to make it easy to follow:

var clone=$('.item-name:last').clone();
clone.insertAfter('.item-name:last');
var attrs='id_form-' + clone.index() + '-name';
clone.find('label').attr('for', attrs);
clone.find('select').attr({id: attrs, name: attrs});
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top