Error concatenating string in jquery

0

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

json[key].id which is integer type

json[key].descricao which is of type string

I have a variable that gets these values like this (just getting the id) and works perfectly:

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

but (I think it's a concatenation error), when I include the description, the code does not work:

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

I get the error:

  

SyntaxError: expected expression, got '}'

    
asked by anonymous 20.01.2018 / 04:11

2 answers

1

Because you are already using single quotation marks in onclick , you can not use the same for the parameters. Use the double quotation marks and escape:

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

I advise you to use Template literals that ends up getting a lot 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 highlight using template literals:

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

See this example:

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);
    
20.01.2018 / 10:24