Error concatenating string in jquery

Asked

Viewed 243 times

0

I have two values I want to include in a string:

json[key].id which is of the integer type

json[key].descricao which is a string

I have a variable that receives these values like this (receiving only the id) and works perfectly:

linha += "<td><a href='#' onclick='excluiFeira(" + json[key].id + ")'>Excluir</a></td>";

however (I think it’s a concatenation error), when I include Description, the code does not work:

linha += "<td><a href='#' onclick='excluiFeira(" + json[key].id + ", '" + json[key].descricao + "')'>Excluir</a></td>";

get the bug:

Syntaxerror: expected Expression, got '}'

2 answers

2

I advise to use Template literals that ends up being much easier to build the strings you want.

In your case it would look like this:

linha += `<td><a href="#" onclick="excluiFeira(${json[key].id},'${json[key].descricao}')">Excluir</a></td>`;

Differences to be highlighted using template literals:

  • The delimiters are now the ` that make it not have to escape ' with \' or escape " with \"
  • Each time you need to put a value inside the string does ${valor}
  • These strings are also multiline allowing you to split the text between several lines if you need to.

See this example working:

let key = 'chave';
let json = {
  chave: {
    id: 36,
    descricao: "teste"
  }
};

let linha = `<td><a href="#" onclick="excluiFeira(${json[key].id},'${json[key].descricao}')">Excluir</a></td>`;
console.log(linha);

1


As you are already using simple quotes on onclick, cannot use the same for the parameters. Use double quotes and make the escape:

linha += "<td><a href='#' onclick='excluiFeira(" + json[key].id +
", \"" + json[key].descricao + "\")'>Excluir</a></td>";
  • worked, only instead of using the simple quotes \', I had to use the double quotes \"

  • can correct the answer I give your points

Browser other questions tagged

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