0

I can't put a title to it. It's inception :)...

I have add div, when it is clicked, it creates alert div. When alert div is clicked it alert me.

that is an example.

$("#add").click(function(){
    $("#add").after("<div class='alert'>Alert</div>");
});

$(".alert").click(function(){
            alert("Here I am");
});

I noticed if I placed a div in the html template as <div class="alert">Alert</div> the alert will work. But if I added the div through the jQuery/JS it will not work.

what is the point of that? to add more inputs and remove it in case he/she added too much, I noticed it didn't work and I wanted to know why:

this is the actual code:

$(document).ready(function(){
    var i           = $("#new_field_count").val();

    //add new field
    $("#addnew_field").click(function(){
        i++;
        $("#new_field").before("<div class='fivepadding'><input name='part1_" + i + "' type='text' placeholder='<?=lang('addform_p1')?>'> = <input name='part2_" + i + "' type='text' placeholder='<?=lang('addform_p2')?>'> <span class='remove clickable'><?=lang('addform_field_remove')?></span> </div>");
            $("#new_field_count").val(i);
    });

    // remove the field
    $(".remove").click(function(){
        i--;
        $(this).parent('div').remove();
        $("#new_field_count").val(i);
    });
});
Abdullah Salma
  • 560
  • 7
  • 20
  • possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Etheryte Jan 03 '15 at 18:33

2 Answers2

2

For dynamically created content, use on.

$("#wrapper-div").on("click", ".alert", function(){
        alert("Here I am");
}; 

Additionally, it's worth mentioning that it is adviced to use on instead of clickfor monitoring for example classes.
Rather than adding an event handler to every class element separately, the click event will bubble to the parent. According to the jQuery docs, it is a good idea to attach the handler to the closest relevant parent element (rather than the document).

html_programmer
  • 18,126
  • 18
  • 85
  • 158
  • Sorry, I had the elements reversed, now it should work. Add the click handler to the closest parent div. If that doesn't work, something else must be going on. – html_programmer Jan 03 '15 at 18:36
0

Your document.ready block is interpreted once the DOM has finished loading. At that point in time, anything not in your DOM cannot have proper event binding. Here you can use delegation to make sure your bindings are going as planned. Since your 'body' will be loaded, you can target your .alert div for clicks as follows:

$("body").on("click", ".alert", function(){
    alert("Here I am");
};
Liam Schauerman
  • 851
  • 5
  • 10
  • 1
    nice! you can also look into jquery's delegate method. That accomplishes the same thing. If the answer is helpful please mark as correct :) – Liam Schauerman Jan 03 '15 at 18:51