H
H
hakkol2015-11-08 11:54:13
JavaScript
hakkol, 2015-11-08 11:54:13

Why alert is called multiple times?

Good day, there is a button that, on click, calls up a form with one button. When you click on the "delete form" button, the form is deleted. When I made a warning window for the delete button, I found the following problem - it can be called several times. If I create 10 forms, then when I click on the delete of the first form, a warning will appear 10 times. Why does the code work the way it does, and how can I fix this problem?

var i = $('.form').size();

    $('#add_form').click(function() {
        i = $('.form:last').attr('id');
        ++i;
        $('<div id="'+ i +'" class="form">\n' +
            '<input type="text" class="form_input form-control" " placeholder="Название формы"/>\n' +
            '<textarea class="form_input form-control" rows="5"  placeholder="Описание формы"></textarea>\n' +
            '<span class="remove_form btn btn-danger">Удалить форму</span>\n' +
            '</div>') .
        fadeIn('slow').appendTo('.all_form');

        $('.remove_form').click(function() {
            if (confirm("Вы хотите удалить форму?") == true) {
                $($(this).parent('.form')).remove();
                i--;
            }
        });

    });

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Ukolov, 2015-11-08
@alexey-m-ukolov

The point is that for some reason you put the removal handler inside the addition handler. You need to do this:

$('#add_form').click(function() {
    var i = ($('.form:last').attr('id') || 0) + 1;
    $('<div id="'+ i +'" class="form">\n' +
        '<input type="text" class="form_input form-control" " placeholder="Название формы"/>\n' +
        '<textarea class="form_input form-control" rows="5"  placeholder="Описание формы"></textarea>\n' +
        '<span class="remove_form btn btn-danger">Удалить форму</span>\n' +
        '</div>')
    .fadeIn('slow').appendTo('.all_form');
});

$('.remove_form').click(function() {
    if (confirm("Вы хотите удалить форму?")) {
        $(this).closest('.form').remove();
    }
});

PS Pay attention, I've corrected some oddities in your code.

D
Denis Ineshin, 2015-11-08
@IonDen

Because you shouldn't create a click remove_formhandler inside a click handler add_form. Take it outside.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question