I have a jQuery code which runs on dom ready. It also creates elements dynamically. When I call the click event of one of these dynamic elements, instead of calling the code inside its click event, it reloads the page and the function on pageload is again called. Basically, it doesn’t run the code inside click event at all.
$(document).ready(function(){
loadPage();
function loadPage() {
var value = $("#search").val();
//create post data
var postData = {
"value" : value
};
//define ajax config object
$.ajax({
type: "post",
url: "search.php",
data: postData,
dataType: "json",
success: function(data) {
if(!data[0].success){
alert(data[0].er);
}
else {
$('#search-results').empty();
var div_main = $("<div>").attr('id', "search-content").appendTo("#search-results");
for (var x = 0; x < data.length; x++) {
var div = $("<div>").attr('id', "search-content-container").appendTo(div_main);
var div_en_quotes = $("<div>").attr('id', "search-en-quotes").html(data[x].cQuotes).appendTo(div);
var div_author = $("<div>").attr('id', "search-author").html(data[x].vAuthor).appendTo(div);
var div_ref = $("<div>").attr('id', "search-bookref").html("<a class='bk_name' href='?bookname="+ data[x].vBookName +"'>" + data[x].vBookName +"</a> "+ data[x].vRef).appendTo(div);
}
}
}
});
}
});
$(document).on("click", "a.bk_name", function(e){
e.preventDefault();
alert($('.bk_name').html());
});
If I add e.preventDefault, it stops the page from reloading and does execute the code, but the value of the anchor tag remains static. That is, it only displays the first value in the loop even if I click on other values.
I’m using jQuery 1.7.
Yes indeed, you do display the value of the first
a.bk_namefound in the DOM. Maybe you mean