Search code examples
javascripthtmlonclickuncaught-exception

How to quote/add javascript variable in html string?


I have tried to use like this

$(nTd).html("<div class='btn-group'> <button class='btn btn-info btn-sm' onclick='viewskpd('"+oData.id+"')' data-toggle='tooltip' title='Detail SKPD'><i class='fa fa-eye' style='color:white'></i></button>");

But it went like this:

<button class="btn btn-info btn-sm" onclick="viewskpd(" 00cc72988f8240428b25ac5327b2a3c6')'="" data-toggle="tooltip" title="" data-original-title="Detail SKPD"><i class="fa fa-eye" style="color:white"></i></button>

But I am not sure why the onclick function that trigger viewskpd() didnt work.

I have checked the console and it tell me like this.

Uncaught SyntaxError: Invalid or unexpected token

Why is this happen ?


Solution

  • The oData.id needs to be quoted so it's a string that is quoted with different quotes than enclosing the onclick attribute:

    onclick='viewskpd(\""+oData.id+"\")'
    

    In full:

    $($0).html("<div class='btn-group'> <button class='btn btn-info btn-sm' onclick='viewskpd(\""+oData.id+"\")' data-toggle='tooltip' title='Detail SKPD'><i class='fa fa-eye' style='color:white'></i></button>");