vygrdev
vygrdev

Reputation: 203

Insert a variable into a template literal href tag

I am trying reference set up an href tag in a template literal using a dynamically generated variable pulled from an AJAX request but can't seem to figure it out. Nothing happens when I click the tagged element and for some reason the <a href/> doesn't show up when I inspect the element on the webpage.

Here is my code:

[...]  

data.forEach(([cafeId, cafeName, cafeAddress]) => {
            var myCol = $('<div id="col"></div>');
            var myPanel = $(
              `
              <div class="card-group">
              <div class="card card-block m-3 overflow-auto" style="width: 18rem;">
                <div class="card-body">
                  <h5 class="card-title venue-name" id=\"` + cafeName + `\"><a href="venue/\"` + cafeId + `\"></a></h5>
                  <h6 class="card-subtitle mb-2 text-muted venue-address"></h6>
                  <div class="dropdown">
                    <div class="venue-options" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></div>
                    <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"><a id="share" class="dropdown-item" href="#">Share</a><a id="addToListNoModal" class="dropdown-item" href="#">Add to List</a></div>
                  </div>
                </div>
              </div>
            </div>
            `
            );
[...]

Here is a JSFiddle: https://jsfiddle.net/50pwyfde/12/

Upvotes: -1

Views: 2267

Answers (3)

Codelleschi
Codelleschi

Reputation: 56

This worked for me:

<a href={https://www.instagram.com/${cafeName}}>

Upvotes: 0

Alrik Zachert
Alrik Zachert

Reputation: 29

There is one double quote too much:

`<a href="venue/\"` + cafeId + `\"></a>`

It has to be:

`<a href="venue/` + cafeId + `\"></a>`

Also, the template literals syntax allows you to embedd your variables instead of concatinating multiple strings.

Like:

`<a href="venue/${cafeId}"></a>`

Checkout this good documentation about template literals: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Upvotes: 0

Barmar
Barmar

Reputation: 781058

You have the wrong number of quotes in the <a> element. You're creating something that looks like

<a href="venue/"cafeId">

The extra quote is causing everything after it to parse incorrectly.

Change that whole line to:

<h5 class="card-title venue-name" id="${cafeName}"><a href="venue/${cafeId}"></a></h5>

Upvotes: 1

Related Questions