1

I'm generating Bootstrap pagination element with PHP within a loop.

<button class="page-link" data-page="'.$page_number.'">'.$page_number.'</button>

The element is generated correctly:

<button class="page-link" data-page="1">1</button>

Then in my script, I need to get this data-page to pass in forward.

I'm trying to do this:

$('#taskcontainer').on("click", $(".page-link"), () => {
       console.log($(this).data("page"));  
    })

But click on those buttons just gives me

undefined

I'm binding to #taskcontainer since this pagination elements are generated by PHP.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Sergei Klinov
  • 730
  • 2
  • 12
  • 25
  • Change jQuery as `$('#taskcontainer').on("click", ".page-link", () => { console.log($(this).data("page")); })` – Rohit Mittal Jun 08 '19 at 12:09
  • @Dharman - The more direct equivalent of `this` if you're not using `this` is `event.currentTarget` rather than `event.target`. – T.J. Crowder Jun 08 '19 at 12:11

1 Answers1

3

There are two problems:

  1. Your delegated handler code is incorrect, you want to pass a selector, not a jQuery object, as the second argument. (See the documentation.)

  2. You're using an arrow function. For this to get set by jQuery, you need a traditional function (more on that in this answer).

So:

$('#taskcontainer').on("click", ".page-link", function() {
// No $( and ) here ------------^^^^^^^^^^^^  ^^^^^^^^^^--- no arrow function here
   console.log($(this).data("page"));  
})

If you want to keep using an arrow function, you can't use this, but you can accept the event parameter and use its currentTarget property:

$('#taskcontainer').on("click", ".page-link", (event) => {
// No $( and ) here ------------^^^^^^^^^^^^  ^^^^^^^--- event parameter
   console.log($(event.currentTarget).data("page"));
// --------------^^^^^^^^^^^^^^^^^^^
})

See also this answer about data vs. attr.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875