Add and Remove Fields with Javascript

Asked

Viewed 10,604 times

3

I need the user to add the same fields as many times as he wants, and also remove them. I was able to 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 does he do

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

2 answers

7


You are using duplicate Ids. The problem is probably with the ID linkRemover.
Ids must be unique, so you should use classes instead of Ids.

Suggestion:

Change html to be inserted from :

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

for

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

And in jQuery/Javascript:

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

for

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

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

Use like 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: http://jsfiddle.net/8k4ooet2/

6

I modified your implementation a little to set the event to remove 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 in jsfiddle

  • @Sergio Bom, this I have already changed to class. Well, but I understand, choose this as an answer and have something wrong like this.

  • @Tuyoshivinicius also thank you for your help :).

  • +1 so have another version of how to solve the problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.