Onclick Javascript not working with "line break"

Asked

Viewed 467 times

0

I’m a problem, I take information entered by the user in the database and put it in a button with onclick for the user to click put it in a modal so that it can edit, I can not put straight into the modal because there are various information then and they have to change depending on where the user clicks, the problem arises when comes information with line break, (the user used a enter during the insertion of the information), the onclick simply does not work and gives an alert: "Uncaught Syntaxerror: Invalid or Unexpected token".
What left me intrigued that with special characters works normally, only with line break that does not. Follows below the button code:

<button class="btnEdit btn btn-primary btn-xs" onclick="editar(\'' + value.nome + '\' , \'' + value.modulo + '\' , \'' + value.roteiro + '\' ,' + value.id + ')"  ><i class="fa fa-edit"></i></button>';
  • then, this enter will generate an "unfinished string constant" in javascript. You have to treat this entry by removing line breaks. Shows how this data is passed to the button.

2 answers

1


So, you have to try to remove these line breaks to not generate error of "constante de cadeia não finalizada" in javascript.

To avoid this error you can eliminate line breaks when you "get the information entered by the user in the database", ie in select, as follows:

SELECT REPLACE(
REPLACE(NOME-COLUNA, '\r', '\\r'),
'\n',
'\\n'
) FROM NOME_TABELA;

Example: table used

inserir a descrição da imagem aqui

Upshot:

inserir a descrição da imagem aqui

Javascript is a single line without breaking and therefore without generating errors.

console.log("Essa coluna tem\r\nquebra de linha\r\nduas veazes\r\nponto final");

However with line break ...

 console.log("Essa coluna tem\r\nquebra de linha\r\nduas 

        veazes\r\nponto final");

0

When you write in HTML the line breaks should be represented by " n", so you should Replace the line break characters by " n". Example:

<html>
<body>
  <input type="button" onclick="alert('Oi, \nTudo bem com você? \n Espero que sim.');" value="Botão" />
</body>
</html>

Replace example if you generate HTML code from Javascript:

variavel.replace("\n","\\n") 
  • Rafael implemented his solution, unfortunately it did not work, may be the format that comes from mysql?

  • Copy the generated code and put as an example in the question. Did you replace the line break as I did in the example? What language do you use ?

  • I took how it looked in the debug, it looked like this: <button class="btnEdit btn-Primary btn-Xs" onclick="edit('teste2' , 'dialer', 'this is a test n test message' ,10,1)"><i class="fa fa-Edit"></i></button>

Browser other questions tagged

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