Home > Blockchain >  How to pass argument from onclick function?
How to pass argument from onclick function?

Time:04-06

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.

CodePudding user response:

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.

  • Related