Adding and Removing Fields with Javascript

2

I need the user to add the same fields as many times as he wants, and also to remove them. I was able to do the script to add the fields, but remove is not working.

HTML

<a href="#" data-id="1" id="adicionarCampo">+ adicionar campo</a>
<form method="POST" action="gerarpdf.php" target="_blank">
    <div id="formulario">
        <input type="text" placeholder="Nº do Documento" maxlength="6" name="numeroDocumento" required/>
        <select name="tipoDocumento" required>
            <option value="" disabled selected>Tipo do Documento</option>
            <option value="01">Volvo</option>
            <option value="02">Saab</option>
        </select>
        <select name="subTipoDocumento" required>
            <option value="" disabled selected>Subtipo do Documento</option>
            <option value="01">Volvo</option>
            <option value="02">Saab</option>
        </select>
    </div>
    <input type="submit" value="Gerar Código"/>
</form>

Javascript

$(function() {
        var divContent = $('#formulario');
        var botaoAdicionar = $('a[data-id="1"]');
        var i = 1;

        //Ao clicar em adicionar ele cria uma linha com novos campos
        $(botaoAdicionar).click(function() {
                $('<div class="conteudoIndividual"><input type="text" placeholder="Nº do Documento" maxlength="6" name="numeroDocumento'+i+'" required/><select name="tipoDocumento'+i+'" required><option value="" disabled selected>Tipo do Documento</option><option value="01">Volvo</option><option value="02">Saab</option></select><select name="subTipoDocumento'+i+'" required><option value="" disabled selected>Subtipo do Documento</option><option value="01">Volvo</option><option value="02">Saab</option></select><a href="#" id="linkRemover">- Remover Campos</a></div>').appendTo(divContent);
                $('#removehidden').remove();
                i++;
                $('<input type="hidden" name="quantidadeCampos" value="'+i+'" id="removehidden">').appendTo(divContent);
        });

        //Cliquando em remover a linha é eliminada
        $('#linkRemover').live('click', function() { 
            $(this).parents('.conteudoIndividual').remove();
            i--;
        });
});

What he does

When I click the adicionar button it creates all 3 fields within a div .conteudoIndividual , I created a hidden field to control that amount of lines.

    
asked by anonymous 03.10.2014 / 14:47

2 answers

6

You are using duplicate IDs. The problem is probably with ID linkRemover . IDs have to be unique, so you should use classes instead of IDs.

Suggestion:

Change the html to be inserted from:

<a href="#" id="linkRemover">

for

<a href="#" class="linkRemover">

And in jQuery / JavaScript from:

    $('#linkRemover').live('click', function() { 

for

    $('.linkRemover').live('click', function() { 

Your second problem is that you have a selector for elements that do not yet exist, you will have to delegate the event.

Use this:

$('#formulario').on('click', '.linkRemover', function() {  // para versão acima do 1.7
$('#formulario').delegate('click', '.linkRemover', function() {  // para versão acima do 1.4

Example: link

    
03.10.2014 / 14:58
5

I've modified your implementation a bit to set the event of removing the div as soon as the line is created.

$(function() {
    var divContent = $('#formulario');
    var botaoAdicionar = $('a[data-id="1"]');
    var i = 1;

    //Ao clicar em adicionar ele cria uma linha com novos campos
    $(botaoAdicionar).click(function() {
        //criando instancia dom .conte4udoIndividual
        var linha = $('<div class="conteudoIndividual"><input type="text" placeholder="Nº do Documento" maxlength="6" name="numeroDocumento' + i + '" required/><select name="tipoDocumento' + i + '" required><option value="" disabled selected>Tipo do Documento</option><option value="01">Volvo</option><option value="02">Saab</option></select><select name="subTipoDocumento' + i + '" required><option value="" disabled selected>Subtipo do Documento</option><option value="01">Volvo</option><option value="02">Saab</option></select><a href="#" id="linkRemover">- Remover Campos</a></div>').appendTo(divContent);
        $('#removehidden').remove();
        i++;
        $('<input type="hidden" name="quantidadeCampos" value="' + i + '" id="removehidden">').appendTo(divContent);

        //recuperando instancia #linkRemover e adicionando evento 
        linha.find("a").on("click", function() {
            $(this).parent(".conteudoIndividual").remove();
        });
    });
});

Example on jsfiddle

    
03.10.2014 / 14:57