Reputation: 7519
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.
Upvotes: 2
Views: 4829
Reputation: 4295
A few things:
I would use a delegate to catch the on click events.
$('#search-results').delegate('a.bk_name', 'click', function(e){
e.preventDefault();
alert($(this).html());
});
$('#search-results').empty(); doesn't do what you are expecting. Probably better to use .html() and pass in the object you are appending.
Upvotes: 1
Reputation: 639
Yes indeed, you do display the value of the first a.bk_name
found in the DOM. Maybe you mean
$(document).on("click", "a.bk_name", function(e){
e.preventDefault();
alert($(this).html()); // instead of alert($('.bk_name').html());
});
Upvotes: 4
Reputation: 28817
The click handler function should return false if you want to prevent default. jQuery internally delegates to preventDefault method, if available.
Upvotes: 1