Quotation marks inside quotation marks and again inside other quotation marks?

Asked

Viewed 8,342 times

3

I have a string variable called [Content] and I want to assign it the tag of a button that calls a javascript. I’m trying this way:

        Conteudo = "<input id='btnOculta_" + lin + "' type='button' value='novo' class='btn btn-default' onclick='Ocultar(this, 'OcultaNovoMedicamento_1')' style='float:left' />"

But in the passage onclick='Hide(this, 'Occult'')' he is understanding the second ' as a closing of the first and not as a second opening. And returns me a whole wrong code.

Expected:

<input id="btnOculta_1" type="button" value="novo" class="btn btn-default" onclick="Ocultar(this, 'OcultaNovoMedicamento_1')" style="float:left" />

Obtained (wrong):

<input class="btn btn-default" id="btnOculta_1" style="float:left"         onclick="Ocultar(this, " type="button" value="novo" ocultanovomedicamento_1')'="">

uHow I fix this cucumber?

2 answers

5


You can use \ for escape those quotes and do like this:

onclick='Ocultar(this, \"OcultaNovoMedicamento_1\")'

Example:

var lin = 2;
var Conteudo = "<input id='btnOculta_" + lin + "' type='button' value='novo' class='btn btn-default' onclick='Ocultar(this, \"OcultaNovoMedicamento_1\")' style='float:left' />";

document.body.innerHTML += Conteudo;

function Ocultar(el, txt) {
  console.log(el.tagName, txt);
}

In modern browsers, or if you’re transposing, you can use template strings like this:

Conteudo = `<input id='btnOculta_${lin}' type='button' value='novo' class='btn btn-default' onclick='Ocultar(this, "OcultaNovoMedicamento_1")' style='float:left' />`
  • Valew @Sergio your first hint using didn’t work... I don’t know how to test running here, rsrs. But the second one worked great! Thank you, you saved me here. In your example there is only one double quote left at the end, but ok.

  • @Still fixed, so are the two examples without bugs :)

1

Try using double quotes with escape in Hiding:

Conteudo = "<input id='btnOculta_'  type='button' value='novo' class='btn btn-default' onclick='Ocultar(this, \"OcultaNovoMedicamento_1\")' style='float:left' />"
  • Thanks @italo this method has a greater compatibility with old browsers right? Very good! Dude where do you learn these secrets? kkkkk!

Browser other questions tagged

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