PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, November 9, 2022

[FIXED] How to pass a parameter and get the event caller JS

 November 09, 2022     html, javascript, jquery, laravel-blade     No comments   

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:

enter image description here

What can I do in that case?

UPD: I'm getting this: enter image description here

But I need THIS: enter image description here


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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing