I can’t remove the fields I just planted

Asked

Viewed 1,056 times

2

I needed 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 entered.

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();
    });
});

2 answers

4

I suggest simplifying your Javascript and avoiding having HTML inside Javascript.

Since most of the code you want to insert already exists the same 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 be an error). Another function/advantage is to create a closure to not pollute the global space with variables defined here.

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

Tie to 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 in the #Dia, looks for the element with class .form-group the closest (looking at the predecessors/parents of the #Dia) and when you find that .form-group make a copy of it

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

Inside that new clone, search for the #Dia and change (or in the case of my example remove) the ID. This is because ID’s have to be unique and because I don’t 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 button #add, also to avoid duplicated ID, and then add the class teste and change the text/html to "Remove Day" instead of "Add Day" which was what had been copied. All this with that copy in memory, before putting on the page.

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

Add this new select, clone of the existing one on the page.

        return false;

Give Return false to prevent it from following the link created by <a> and not load the page erasing everything.

    });

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

Here I add event delegation. I’m using . on() to delegate the event but you can use . live() if you are using an old version of jQuery. However, what was missing on that line was to delegate the event. Since there was no class element yet .teste when . live() has been read, the code does not know it exists. So if the code is "listening" to events on #campos, when the click appears it will find the selector that is in the 2nd parameter of the function: .teste and there you can find it. You can read more about this in my reply here: /a/5199/129 .

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

When the element above receives the click, look for the nearest relative with the class .form-group and remove it from the page.

    });
});
  • 1

    Dude! This code was show ball, worked perfectly and simplified a lot, but I do not understand this part of javascript I do not know anything, so I think I will only be able to use so when you are deeper in the subject... But thank you!!

  • 2

    @Alceu, my answer is better for two reasons. First, because it doesn’t mix HTML within Javascript. Second because it is less customized, less difficult to maintain. I added a very detailed explanation to better understand the code.

2


There are some problems in your code:

  1. The method .live jQuery was discontinued in version 1.7 of the library and should no longer be used, as shown in documentation. In its place you can use the on(), that was added in jQuery version 1.7.
  2. Your Rent selector is actually well-intentioned, but there is a primary and common error even among experienced developers: you forgot to put the . on the dial of class:

    // 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 posted an example here for you to see in operation.

  • Ball show, it worked, the mistakes were these same!! I’m already able to insert and remove now!! Thanks!

Browser other questions tagged

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