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

Tuesday, April 19, 2022

[FIXED] How to pass argument from onclick function?

 April 19, 2022     function, javascript, jquery, laravel, onclick     No comments   

Issue

I have created a table and populated it using jQuery. Now I would like to add a text such as when we click on it a function executes. I have used onclick and it worked fine, but I also need to send a few arguments to my function, how can I send arguments to the targeted function from onclick:

var dataHtml = '';
$.each(data, function (index, user) {
    dataHtml+="<code onclick=show_popup(1,user['donner'][0])> Donner details</code>";
});
$("#t-data").html(dataHtml);

function show_popup(show=0, donner){
    $(document).ready(function(){
    var showModel=show;
    if(showModel==`1`){
        $(`#modal-default-admin`).modal(`show`);
    }
});

But it shows a "user is not defined" error. User is defined and I also can access it.


Solution

The user is in fact not defined. The problem you are facing is that you are using HTML as a string, so you are providing onclick=show_popup(1,user['donner'][0]) as string. When jQuery "makes HTML" out of this string and you click on it, it calls show_popup with 1 and user['donner'][0] and the user here is undefined. It was only available inside the $.each loop, not outside of it.

The simplest fix is to pass the value directly and not trying to do it as a pointer.

onclick=show_popup(1,\""+ user['donner'][0] +"\")>

Like this, it will use the value of user['donner'][0] when creating the HTML.

Bonus point: You should wrap the onclick attribute with quotes:

dataHtml += "<code onclick='show_popup(1,\""+ user['donner'][0] +"\")'> Donner details</code>";

Just to make sure that for example a space in the value of user['donner'][0] doesn't break it again.



Answered By - Jakub Kotrs
Answer Checked By - Dawn Plyler (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