1

How to get the id in jquery "on" function as in javascript onclick function ? thanks in advance

html

@foreach ($datas as $key=>$data)
    <Button onclick="viewReturn('{{$data->id}}')" class="get-data">Save</Button>
@endforeach

javascript

function viewReturn(id) {
    $.ajax({
        method: 'Get',
        url: basePath + "getData/" + id,
    })
}

jquery

$(document).on('click', 'get-data', function(){
    //how to get $data->id here?
})
Amrita Stha
  • 2,973
  • 3
  • 25
  • 46
  • 1
    Your selector `'get-data'` implies that you have a `` element. A class selector would look like `".get-data"`. Consider using a `data-*` attribute like `data-id="{{$data->id}}"` and getting `$(this).data("id")`. – Sebastian Simon Jun 02 '21 at 08:27

1 Answers1

2

To convert the code at the top to using a delegated jQuery event handler, you need to:

  1. Put the id value in a data-* attribute
  2. Add a . on ".get-data" so it's a class selector, not a tag selector
  3. Get the data-* attribute from the element

#1 looks like this:

@foreach ($datas as $key=>$data)
    <Button data-id="{{$data->id}}" class="get-data">Save</Button>
@endforeach

#2 and #3 look like this:

$(document).on("click", ".get-data", function(){
    const id = this.getAttribute("data-id");
    // ...use `id`...
});

or on any even vaguely modern browser (we're talking IE11+), you can use dataset rather than getAttribute:

$(document).on("click", ".get-data", function(){
    const id = this.dataset.id;
    // ...use `id`...
});

Side note: You will have people telling you to use the jQuery data function. There's no reason to do that in what you've posted (though it would work). data is not just an accessor for data-* attributes, it's both more and less than that.

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