1

I have a few buttons generated in this Javascript method, and one of them has onclick() handler where I need to pass a string as an input parameter.

function ShowButtons() {
  let $previewDiv = $("#ServicesPreview");
  $previewDiv.html("<button id='myBtn' onclick='CheckID('MYID')'></button>")
}

I can't enclose the string in single quotes because it produces this on the website, and I get the error "Unexpected end of input":

<button id="myBtn" onclick="CheckID(" MYID')'></button>

I've also tried no quotes, and I can't use double-quotes because that terminates the string being passed into the jQuery.html method. What's the proper syntax here?

isherwood
  • 58,414
  • 16
  • 114
  • 157
Matt
  • 109
  • 1
  • 12
  • 3
    `$previewDiv.html(\`\`)` – Jaromanda X Jun 29 '21 at 16:43
  • 4
    Slightly off topic: *how do I do this* you don't (not anymore). Use a proper event handler and pass in your data via data-attributes, eg `$previewDiv.html(""); $("#myBtn").click(function() { var id = $(this).data("id"); CheckID(id); });` – freedomn-m Jun 29 '21 at 16:53
  • @JaromandaX Using backticks worked! I was not familiar with that syntax! Thank you! – Matt Jun 29 '21 at 18:05
  • @HereticMonkey & James: I was able to get it to work by enclosing the outer string with backticks. That was a javascript syntax I was not familiar with before asking this question. – Matt Jun 30 '21 at 20:10

1 Answers1

1

freedomn-m's comment is correct: you're better off setting a click handler using JavaScript. I'd do it more like this:

function ShowButtons() {
  let $button = $("<button></button>");
  $button.click(() => CheckID("MYID"));
  $("#ServicesPreview").empty().append($button);
}

You'll find this pattern gives you a lot more flexibility to componentize your code in the long run. It's better to avoid relying on HTML IDs since they have to be unique across the DOM, so they're kind of like global variables.

But if you have to stick with the pattern you're asking about, the way to address quotes in quotes is to escape the quotes for the context that they're in. Since your quotes are inside HTML, you can use HTML escaping:

function ShowButtons() {
  let $previewDiv = $("#ServicesPreview");
  $previewDiv.html("<button id='myBtn' onclick='CheckID(&quot;MYID&quot;)'></button>")
}

Or, since you're in JavaScript, you could escape the JavaScript double-quotes.

function ShowButtons() {
  let $previewDiv = $("#ServicesPreview");
  $previewDiv.html("<button id='myBtn' onclick='CheckID(\"MYID\")'></button>")
}

Or you could use back-ticks in the first place so the double-quotes don't need escaping.

function ShowButtons() {
  let $previewDiv = $("#ServicesPreview");
  $previewDiv.html(`<button id='myBtn' onclick='CheckID("MYID")'></button>`)
}
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315