Issue
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?
Solution
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 class="btn btn-primary" onclick="addToCart('id', this)">click to replace</button>
Answered By - Diego D Answer Checked By - Clifford M. (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.