Get value in onclick js

Asked

Viewed 587 times

0

I have the following variable:

var id = doc.data().cd_id ;

Already in Javascript I dynamically mount html:

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

My Function:

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

The following error occurs:

Uncaught SyntaxError: Invalid or unexpected token

My id has the following value: 4eCj7NkX9liruvf8izgF

  • 2

    Just with the information that this here is not possible to tell where this error.

1 answer

2


missing double quotes, put them escaping them that way

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

Testing

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>");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.