0

I have created a search page that has on top and bottom page navigation. This is a simplified version just to show my problem:

$(function(){
$("select").on("click" , function(){
    if ($(this).val() == 10){
        var total_pages = 3;
        }
    else{
        var total_pages = 5;
        }
    var pages = "";

    for (var i = 1; i <= total_pages; i++)  {
        var pages = pages + "<span class='page'>" + i + "</span>";
        }
    $(".pagination").html(pages);
    });
$("select").click();

$(".page").on("click" , function(){
    alert($(this).text());
    });
});

And you can try it yourself here:

JSFiddle

In this example you have 5 pages when you select 10 items per page and 3 pages for 20 results per page. But when you select an other value per page the alert function doesn't show up anymore. It seems that changes, after the document is loaded, are not being noticed by the document.ready function.

I searched and saw a lot of familiar questions and their solutions. I can imagine also some alternatives but not the one who can satisfy me. Because unfortunately I don't know now a simple solution without a lot of extra code with id's, classes, data-attributes etc. Who can contribute me some knowledge for a good solution?

Dinizworld
  • 394
  • 1
  • 6
  • 16
  • 1
    http://jsfiddle.net/hQ7Ee/ – Jason P Feb 05 '14 at 19:40
  • possible duplicate of [In jQuery, how to attach events to dynamic html elements?](http://stackoverflow.com/questions/1359018/in-jquery-how-to-attach-events-to-dynamic-html-elements) – Jason P Feb 05 '14 at 19:41
  • Learn [**Event Delegation**](http://learn.jquery.com/events/event-delegation/) – Satpal Feb 05 '14 at 19:42

2 Answers2

2

That's because when you do this:

$(".pagination").html(pages);

You remove old DOM elements and it's "click" functions and replace it with new HTML.

Add this:

$(".page").on("click" , function(){
    alert($(this).text());
    });

right after first line I mentioned

Ivan Mukho
  • 36
  • 5
0

Event delegation is a good practice when you deal with dynamic content. In your case, you can attach the click event to the parent.

I just tweaked one line in your original code:

$(".pagination").on("click" , ".page" , function(){
  alert($(this).text());
});

Live demo: http://jsfiddle.net/zkDF4/6/

Christophe
  • 27,383
  • 28
  • 97
  • 140