Answer the question
In order to leave comments, you need to log in
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
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();
}
});
Because you shouldn't create a click remove_form
handler inside a click handler add_form
. Take it outside.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question