Sergei Klinov
Sergei Klinov

Reputation: 798

Can't read data- attribute with Jquery

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.

Upvotes: 1

Views: 102

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075527

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.

Upvotes: 3

Related Questions