I need to pass parameter from HTML to the JS function. I can't set unique id, because elements are in loop. So it looks like this:
@foreach ($meals as $meal)
<button class="btn btn-primary" onclick="addToCart('{{ $meal->id }}')">
@endforeach
But in calling function, I need access both to input parameter and event caller:
let addToCart = (id, caller) => {
console.log(id);
console.log(caller);
}
I tried to put this
as second parameter, when calling function:
<button class="btn btn-primary" onclick="addToCart('{{ $meal->id }}', this)">
Well, it works, but my next task is to replace event caller with some other DOM element, using JQuery.
let addToCart = (id, caller) => {
caller.replaceWith("<h1>helloworld</h1>");
}
Unfortunately that replaces event caller with that, only as innerHTML of parent element, without interacting with tags. So, I'm getting smthing like this:
What can I do in that case?
window.event.target
orwindow.event.currentTarget
(this second option is safer in case the event will bubble to the parent). You solved anyway passingthis
when invoking the handler. But the final issue is unclear. Your handler literally replaces the event target (the button firing the click event) with a custom html and it behaves as expected.