Get value in onclick js

0

I have the following variable:

var id = doc.data().cd_id ;

In JavaScript, I dynamically add html:

"<button type='button' onclick='testeonclick(" + id + ")' class='btn btn-primary col-xs-12'>Editar Produto </button>"

My Role:

function testeonclick(id){
  alert(id);
}

The following error occurred:

Uncaught SyntaxError: Invalid or unexpected token

My id has the following value: 4eCj7NkX9liruvf8izgF

    
asked by anonymous 24.10.2018 / 01:17

1 answer

2

Double quotes are missing, put them escaping them this way

onclick='testeonclick(\"" + id + "\")'

Test

function testeonclick(id){
  alert(id);
}
var id = "4eCj7NkX9liruvf8izgF";

//erro
console.log("ERRADO \n<button type='button' onclick='testeonclick(" + id + ")' class='btn btn-primary col-xs-12'>Editar Produto </button>");

//correto
console.log("CORRETO \n<button type='button' onclick='testeonclick(\"" + id + "\")' class='btn btn-primary col-xs-12'>Editar Produto </button>");

document.write("<button type='button' onclick='testeonclick(\"" + id + "\")' class='btn btn-primary col-xs-12'>Editar Produto </button>");
    
24.10.2018 / 03:47