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 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 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?
CodePudding user response:
In case you meant to replace the button that fired the click event with a different html object instead of just replacing its text content like you did in your example, the key was using replaceWith
on a jQuery object instead of calling it from an HTMLDocument.
The difference between https://developer.mozilla.org/en-US/docs/Web/API/Element/replaceWith and https://api.jquery.com/replacewith/
So to force the invocation from the jQuery object, just use $(caller)
let addToCart = (id, caller) => {
$(caller).replaceWith( "<h1>helloworld</h1>" );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="addToCart('id', this)">click to replace</button>