To convert the code at the top to using a delegated jQuery event handler, you need to:
- Put the
id value in a data-* attribute
- Add a
. on ".get-data" so it's a class selector, not a tag selector
- 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.
'get-data'implies that you have a<get-data>element. A class selector would look like".get-data". Consider using adata-*attribute likedata-id="{{$data->id}}"and getting$(this).data("id").