I can not remove the fields I just placed

2

I need to insert some fields dynamically and I found a video lesson that showed how to do it. However, after doing everything right, my code does not remove the ones I just inserted.

Where is the error?

Here is the code:

<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/addcampo.js"></script>

<form class="form-horizontal">
    <fieldset>
    <!-- Form Name -->
    <legend>Professores > Novo Professor</legend>

    <!-- Text input-->
    <div class="form-group">
        <label class="col-md-4 control-label" for="Professores">Nome</label>  
        <div class="col-md-6">
            <input id="Professores" name="Professores" type="text" placeholder="Professor" class="form-control input-md">
        </div>
    </div>

    <!-- Select Basic -->
    <div class="form-group">
    <label class="col-md-4 control-label" for="Dia">Dia disponível</label>
        <div class="col-md-4">
            <select id="Dia" name="Dia" class="form-control">
            <option value="Segunda">Segunda-Feira</option>
            <option value="Terça">Terça-Feira</option>
            <option value="Quarta">Quarta-Feira</option>
            <option value="Quinta">Quinta-Feira</option>
            <option value="Sexta">Sexta-Feria</option>
            <option value="Sabado">Sábado</option>
            </select>
        </div>
        <div class="col-md-1">
            <a href="#" id="add" class="btn btn-primary" role="button">Adicionar Dia</a>
        </div>
    </div>

    <!-- Multiple Checkboxes (inline) -->
    <div class="form-group">
        <label class="col-md-4 control-label" for="Turno">Turno</label>
        <div class="col-md-4">
            <label class="checkbox-inline" for="Turno-0"><input type="checkbox" name="Turno" id="Turno-0" value="Manha">Manhã</label>
            <label class="checkbox-inline" for="Turno-1"><input type="checkbox" name="Turno" id="Turno-1" value="Tarde">Tarde</label>
            <label class="checkbox-inline" for="Turno-2"><input type="checkbox" name="Turno" id="Turno-2" value="Noite">Noite</label>
        </div>
    </div>

    <div id="campos"></div>

    <!-- Button (Double) -->
    <div class="form-group">
        <label class="col-md-4 control-label" for="Salvar"></label>
        <div class="col-md-8">
            <button id="Salvar" name="Salvar" class="btn btn-success">Salvar</button>
            <button id="Cancelar" name="Cancelar" class="btn btn-danger">Cancelar</button>
        </div>
    </div>

    </fieldset>
</form>
$(function(){
    $("#add").click(function(){
        var input =  '<div class="dias">'
            input += '<div class="form-group">'
            input +=             '<label class="col-md-4 control-label" for="Dia">Dia disponível</label>'
            input +=                '<div class="col-md-4">'
            input +=                    '<select id="Dia" name="Dia" class="form-control">'
            input +=                    '<option value="Segunda">Segunda-Feira</option>'
            input +=                    '<option value="Terça">Terça-Feira</option>'
            input +=                    '<option value="Quarta">Quarta-Feira</option>'
            input +=                    '<option value="Quinta">Quinta-Feira</option>'
            input +=                    '<option value="Sexta">Sexta-Feria</option>'
            input +=                    '<option value="Sabado">Sábado</option>'
            input +=                    '</select>'
            input +=                '</div>'



            input +=        '</div>'

            input +=         '<!-- Multiple Checkboxes (inline) -->'
            input +=         '<div class="form-group">'
            input +=            '<label class="col-md-4 control-label" for="Turno">Turno</label>'
            input +=                '<div class="col-md-4">'
            input +=                    '<label class="checkbox-inline" for="Turno-0"><input type="checkbox" name="Turno" id="Turno-0" value="Manha">Manhã</label>'
            input +=                    '<label class="checkbox-inline" for="Turno-1"><input type="checkbox" name="Turno" id="Turno-1" value="Tarde">Tarde</label>'
            input +=                    '<label class="checkbox-inline" for="Turno-2"><input type="checkbox" name="Turno" id="Turno-2" value="Noite">Noite</label>'
            input +=                '</div>'
            input +=        '</div>'
            input +=                '<a href="#" id="deletar" class="teste" role="button">Adicionar Dia</a>'
            input +='</div>';

        $("#campos").append(input);
        return false;
    });

    $('.teste').live('click', function(){
        $(this).parent('dias').remove();
    });
});
    
asked by anonymous 15.04.2014 / 04:13

2 answers

2

There are some problems with your code:

  • The .live method of jQuery has been deprecated in version 1.7 of the library and should no longer be used, as shown in documentation >. Instead you can use on () , which was added in jQuery version 1.7.
  • Your selector in parent is well-intentioned, but there is a primary and common error even among experienced developers: you forgot to put . in the class selector:

    // Você esqueceu do ".", para indicar que se trata de uma class       
    $(this).parent('.dias').remove();
    
  • Making these changes is for your code to work perfectly. I've put an example here to see it working.

        
    15.04.2014 / 04:51
    4

    I suggest simplifying your JavaScript and avoid having HTML within JavaScript.

    Since most of the code you want to insert already exists on the page you can copy instead of writing HTML in the middle of JavaScript.

    Suggestion:

    $(function () {
        $("#add").click(function () {
            var formGroup = $('#Dia').closest('.form-group').clone(); // criar uma cópia do outro select
            formGroup.find('select').prop('id', ''); // retirar a ID (ou dar um index) porque IDs têm de ser únicas
            formGroup.find('#add').prop('id', '').addClass('teste').html('Remover dia'); // mudar o link de adicionar para remover
    
            $("#campos").append(formGroup);
            return false;
        });
    
        $('#campos').on('click', '.teste', function () { // usando delegação do evento e o .on()
            $(this).closest('.form-group').remove();
        });
    });
    

    Demo

    Explanation of the code:

    $(function () {
    

    This first line is for the code to run only when the page has loaded, to prevent the code from running before the HTML exists (which would give error). Another function / advantage is to create a closure to not pollute the global space with variables defined here.

        $("#add").click(function () {
    

    Tying the element that has the ID #add a function that runs when the element receives a click

            var formGroup = $('#Dia').closest('.form-group').clone(); // criar uma cópia do outro select
    

    As I commented in the code, this creates a copy / clone of your select that already exists on the page. The selector starts at #Dia , looks for the element with the closest .form-group class (looking at the predecessors / parents of #Dia ) and when it finds that .form-group makes a copy of it

            formGroup.find('select').prop('id', ''); // retirar a ID (ou dar um index) porque IDs têm de ser únicas
    

    Within this new clone, look for #Dia and change (or in case of my example to remove) the ID. This is because ID's have to be unique and because I do not want to put it on the page with duplicate ID.

            formGroup.find('#add').prop('id', '').addClass('teste').html('Remover dia'); // mudar o link de adicionar para remover
    

    Here I do the same for the #add button, also to avoid duplicate ID, and then add the teste class and change the / html text to "Remove Day" instead of "Add Day" which was what had been copied. All this with this copy in memory, before putting it on the page.

            $("#campos").append(formGroup);
    

    Add this new select, existing clone, to the page.

            return false;
    

    Give false return to prevent it from following the link created by <a> and not loading the page by deleting everything.

        });
    
        $('#campos').on('click', '.teste', function () { // usando delegação do evento e o .on()
    

    Here I add delegation of events. I am using .on () to delegate the event but can use .live () if you are using an older version of jQuery. But what was lacking in that line was to delegate the event. Since there was not yet an element with class .teste when .live () was read, the code does not know that it exists. So if the code is "listening" to events in #campos , when the click appears it will look for the selector that is in the 2nd parameter of the function: .teste and there you will find it. You can read more about this in my answer here: link .

            $(this).closest('.form-group').remove();
    

    When the element above receives the click, it looks for the closest relative with the class .form-group and removes it from the page.

        });
    });
    
        
    15.04.2014 / 10:15