Reputation: 924
As title above. My click event is not hitting when i click my button. I made my button via JS Loop
. My click event function is in outside of my loop function. As I notice when i am debugging, when i try to put it inside the function of the loop the click function it's hitting properly now.
Is there any reason why?
for (var i = 0; i < dataLength; i++) {
var docsLength = data.data[i].resultData;
var title = data.data[i].resultData[i].Type.Description;
var card = '<div class="card" id="HelloWorld_' + i + '"> <div class="card-header bg-success"><h3 class="card-title">' + title + ' </h3 ></div> <div class="card-body"> </div>'
$("#card_documents > .card-body").append(card);
for (var b = 0; b < docsLength.length; b++) {
var id = "HelloWorld_" + i;
var row = '<div class="row mt-2" style="font-size:20px">'
+ '<div class="col-md-1"><input type="checkbox" style="height:20px; -webkit-box-shadow:none" class="form-control flat mt-2"> </div >'
+ '<div class="col-md-1"> <input type="button" id="btnClickHello' + b + "" + i + '" value="Upload"></div>'
+ '<div class="col-md-10" style="color:green"> ' + data.data[i].resultData[b].Docs + ' </div >'
+ '</div >';
$("#" + id + " > .card-body").append(row);
}
}
$("#btnClickHello21").click(function (e) {
e.preventDefault();
alert("a");
});
Upvotes: 0
Views: 59
Reputation: 3922
as per my knowledge it is not hitting because you are not wrapping your function within a document.ready(). DOM and function is loaded before you create a button.
you need a event delegation concept like.
$(document).ready(function(){
$("#btnClickHello21").on('click',function(){
//do your stuff.
});
})
Upvotes: -1
Reputation: 765
You are adding element dynamically, that is why click
event is not working beacuse all click
events get bind to DOM on load. To enable click
on dynamically added element you can use below code -
$('body').on('click', '#btnClickHello21', function(e) {
e.preventDefault();
alert("a");
});
This will work for all a tags with #btnClickHello21
in the body, whether already present or dynamically added later.
Upvotes: 1
Reputation: 2414
Another way of doing it (despite the 2 answers already), is by wrapping your click event function into a document.ready
function.
$( document ).ready(function() {
$("#btnClickHello21").click(function (e) {
e.preventDefault();
alert("a");
});
});
jQuery document.ready docs: http://learn.jquery.com/using-jquery-core/document-ready/
Upvotes: 1
Reputation: 28455
For dynamically added elements, you need to use jQuery.on
$(".card-body").on("click", "#btnClickHello21", function (e) {
e.preventDefault();
alert("a");
});
Upvotes: 1