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?
})
1
  • 1
    Your selector 'get-data' implies that you have a <get-data> element. A class selector would look like ".get-data". Consider using a data-* attribute like data-id="{{$data->id}}" and getting $(this).data("id"). Commented Jun 2, 2021 at 8:27

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.