1

I'm trying to build a string inside <script></script> which has a variable.

var buildurl = response.show.url;
var connectHtml = '<button class="form_button" id="connectButton" onclick="window.location='+buildurl+'">Connect</button>'
$('#someElement').html(connectHtml);

When I inspect the element, I see the url built but without the single quotes (''). So when I click on the button, it does not navigate to the url. How can I add the '' to get

onclick="window.location='https://something.com/admin/one/two/123/456'" ?

<button class="form_button" id="connectButton" onclick="window.location=https://something.com/admin/one/two/123/456">Connect</button>
6
  • Why not just make a function that redirects and then call that onclick? Commented Sep 12, 2019 at 17:07
  • @FunkDoc Even if I were to move the "window.location" inside a function, I would still face the issue of missing single quotes. I am not able to add the quotes to the string using a concatenation operator. Commented Sep 12, 2019 at 17:11
  • 1
    Trying to find a good duplicate (I imagine there is one), but in the meantime, onclick="window.location=\''+buildurl+'\'" Commented Sep 12, 2019 at 17:12
  • @PatrickQ Here's another way I found - stackoverflow.com/questions/10787393/… . thanks! Commented Sep 12, 2019 at 17:15
  • Which ever quotes you're using as delimiter for your string have to be escaped when you want to use them in that same string. Commented Sep 12, 2019 at 17:15

1 Answer 1

1

You can use template literals and not worry about apostrophes and quotes:

`<button class="form_button" id="connectButton" onclick="window.location='${buildurl}'">Connect</button>`
Sign up to request clarification or add additional context in comments.

1 Comment

@PatrickQ good point, thank you. It's fixed now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.