Passing a javascript parameter in the middle of an append

1

Without much fanfare, I'm stuck on the following problem:

I have the following JS code:

data.forEach(function(item) {
        $("#bodyTabelaClientes").append(
            "<tr><td style = 'text-align: center'>" + item.nome 
            + "</td> <td style = 'text-align: center'> " + item.telefone 
            + "</td> <td style = 'text-align: center'> " + item.cep 
            + "</td> <td style = 'text-align: center'>" + item.endereco 
            + "</td> <td style = 'text-align: center'><button class = 'btn btn-success btnSelecionarCliente'  onclick='selecionarCliente("+item+")'>Selecionar</button></tr>");
    });

My problem is in the button inside the append, I need to pass this 'item' parameter as parameter to another function, to get the data of this item and do something with them, however, when clicking, the console accuses

  

Uncaught SyntaxError: Unexpected identifier

with a blank page. I think it's some mistake with the quotes, but I could not identify, does anyone have any idea what to do? Thanks!

    
asked by anonymous 15.05.2017 / 19:03

1 answer

2

You will not be able to get HTML to pass the function to an entire object, I suggest you pass the whole object as a text argument.

Example

var data = [{
  nome: 'Lucas',
  telefone: '12',
  cep: '123',
  endereco: '123'
}]
data.forEach(function(item) {
  $("#bodyTabelaClientes").append(
    "<tr><td style = 'text-align: center'>" + item.nome +
    "</td> <td style = 'text-align: center'> " + item.telefone +
    "</td> <td style = 'text-align: center'> " + item.cep +
    "</td> <td style = 'text-align: center'>" + item.endereco +
    "</td> <td style = 'text-align: center'><button class = 'btn btn-success btnSelecionarCliente'  onclick='selecionarCliente(\"" + encodeURIComponent(JSON.stringify(item)) + "\");'>Selecionar</button></tr>");
});

function selecionarCliente(item) {
  var objeto = JSON.parse(decodeURIComponent(item));
  console.log(objeto);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><table><tbodyid="bodyTabelaClientes">
  </tbody>
</table>

If you only convert the object to string using stringify , there will be a problem with escapes, so I used encodeURIComponent so that the string that will be sent as an argument is encoded; so in the function that will be called I used the encodeURIComponent , which will convert to the text again, and then JSON.parse to go back to the object.

    
15.05.2017 / 19:25