Event problems in dynamically created elements

Asked

Viewed 1,392 times

5

My intention is:

A listing where it is possible to add <div> and delete the added Divs with a "button" inserted into each div.

The page already comes with some divs fixed inserts which are equal to those to be added.

The point is, in the divs that are already on the page, the erase button works correctly, now the divs which are inserted with prepend are not deleted. I have checked the function of the remove() and all the divs both fixed and added have the same class. Finally...

list-mode is the div which encompasses all of these divs in html, .img_des_row is the div which must be repeated and erased... Recalling: the addition is working properly!

Javascript:

$("#bt-adicionar-imagens").click(function() {
    $(".list-mode").prepend("< div class='img_des_row col-xs-12'>< div class='col-xs-8 no-pad-left'>< div class='description_img'>Lorem ipsum dolor sit amet consectetur adipisicing elit, sed do elusmod tempor.< /div>< /div>< div class='col-xs-2'><div class='pull-right margin-top_20 dropdown'><a href='#' class='icon-dwn-med pull-left margin_l_r_5'>< /a>< a href='#' class='icon-edit-med pull-left margin_l_r_5 dropdown-toggle' data-toggle='dropdown'>< /a>< div class='dropdown-menu alt-color-scheme left pad'>< /div>< a href='#' class='icon-trash-med pull-left margin_l_r_5'>< /a>< /div>< /div>< /div>");
});

$('.img_des_row .icon-trash-med').on('click', function(e) {
    $(this).closest(".img_des_row").remove();
});
  • If I can create a jsFiddle (and also post your html here in question), with a representation of your real problem, with your html and your JS, so we can try to help you, and also your question is not very confusing, try to reread and try to improve it. And take a look at us markdown here from the site, I formatted your code and some of your question to make it easier to read

  • Thanks Fernando. I retreated 4 spaces and was not, probably got it wrong and then I opened the <div> to show the code, thanks for helping. I will use jsFiddle.

1 answer

9


Here’s the thing, if I understand what you want. Your code has the following problems:

  • Your event selector on() is not prepared to work with dynamic elements;
  • Your code html, You’re having some problems, like you have some spaces before div, like this: < div>< /div>, and the right thing would be <div></div> (maybe this is not a problem in your environment, but here for me in Chrome, this was not interpreted as html rather with text);

Then I solved the event selector problem on(), for dynamic elements like this:

$('.list-mode').on('click', '.img_des_row .icon-trash-med', function(e) {
    $(this).closest(".img_des_row").remove();
});

What happens and that method on(), works as follows to capture elements created dynamically:

I’ll try to explain in parts:

// o seletor onde o 'on()' é aplicado deve ser um elemento estático, que já exista
// quando a associação do evento seja executado, no caso a 'div' ('.list-mode') 
// onde os elementos dinâmicos serão inseridos.
$('.list-mode')

// o primeiro parâmetro é o evento, no caso o 'click'
// o segundo é o seletor "dinâmico", no caso '.img_des_row .icon-trash-med'
// (eu penso assim: esse seletor secundário será executado a cada evento (no caso click) no seletor (principal('.list-mode')) onde o 'on()' foi aplicado)
// e por ultimo a função de callback do evento (o handler)
.on('click', '.img_des_row .icon-trash-med', function(){...});

I do not know if it was clear my explanation, any doubts about the method on() you can consult on documentation of the method on().

And to stay but easy to understand I created a example of the working solution

And if that’s not exactly what you needed to comment on.

  • Fernando, valeuzão, solved my problem. The separate div was to show the code, because I didn’t know how to insert it right and so it interpreted and only showed the text. Obligatory.

  • @user49915, I’m glad it worked out and I could help you.

  • 1

    It is very common that events do not work in dynamic elements when an AJAX request is made. And only with on() to solve it. @Fernando, it was a beautiful explanation!

  • Fernando, your explanation about the On() method was the best I could find. I was also having the same problem. But in my case it was just a confusion regarding the parameters that was passing to the method. Thank you very much!

Browser other questions tagged

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