How to add and remove fields generated via CakePHP, dynamically?

1

Hello.

I have a <select> that is fed by data from the database. I need to manipulate this select and multiply it if the user wants to send two different data. Since the <option> s depends on the data coming from the database, I do not have the option to use $(elemento).append('<select>...</select>');

I also need to change the "name" attribute of each <select> so I can get the values correctly in $this->request->data .

<div class="form-group">
    <div class="col-lg-11">
        <select class="form-control name="data[Model][0][sl_dinamica]" select-a-ser-replicada">
            <option value="1">Valor 1</option>
            <option value="2">Valor 2</option>
            <option value="3">Valor 3</option>
        </select>
        <span class="btn-apagar"></span>
    </div>
    <div class="col-lg-1">
        <span class="btn-adicionar"></span>
    </div>
</div>
    
asked by anonymous 11.12.2014 / 13:42

1 answer

2

You can use this:

$('.btn-duplicar').on('click', function(){
    var select = $(this).parent().prev().find('select:first'); // ir buscar o original
    var novoSelect = select.clone().attr('name', 'novo_select'); // criar uma cópia e mudar o nome
    $(select).after(novoSelect); // inserir depois do select original
});

Some decisions you will have to make:

  • In the example of "new_select" as the name of the new select. You can change how you will generate this if you generate more than one duplicate

  • I created a button to duplicate it, you might have another one that did not show in the question. If it is not the sibling / sibling of the select tell me to adjust the answer.

  • If the "duplicate" button itself is added dynamically, it must use delegation. You can replace the first line with:

    $(document).on('click', '.btn-duplicar', function(){

Example: link

    
11.12.2014 / 14:28