Pass a javascript parameter in the middle of an append

Asked

Viewed 389 times

1

Without too much hustle, 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 the button inside the append, I need to pass this parameter 'item' as parameter to another function, to take 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 believe it’s a mistake with the quotes, but I couldn’t identify it, does anyone have any idea what to do? Thank you!

1 answer

2


You won’t be able to get HTML to pass an entire object to the function, I suggest you pass as argument the full text object.

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>
  <tbody id="bodyTabelaClientes">
  </tbody>
</table>

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

  • 1

    It paid off, it worked perfectly and the explanation in the end also made a difference. Thank you.

Browser other questions tagged

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