Reputation: 183
I'm trying to write JS code and I have to concatenate multiple strings with variables in them to form a giant string.
var another_class = 'datatables-more';
var color = "#e07c8a";
var NYC = "New York City";
var LA = "Los Angeles";
var url = "/my/app/url2";
var some_url = "/my/app/url";
var row_count = row['available_count'];
data = '<td><div class="' + another_class + 'item-count-div" style="background-color:' + color + '"' + ' data-url="' + url + '"' + ' data-toggle="popover" data-content="" + row_count + '</div></td>';
Now, for the data-content
attribute, I want it's value to be:
data-content = "<a href="some_url">NYC</a> <a href="some_url">LA</a>"
some_url
, NYC
, LA
are all variables. How can I achieve this result? I'm having a hard time figuring this out.
I have tried to do this:
data-content="<a href="'+some_url+'">'+NYC+'</a>"'
This didn't work and gives me weird ahref
tag.
Upvotes: 0
Views: 1026
Reputation: 846
If you are using newer version, you can refer to the previous answer, otherwise you can do something like:
Update: Following code works perfectly. It was html causing issue.
var another_class = 'datatables-more';
var color = "#e07c8a";
var NYC = "New York City";
var LA = "Los Angeles";
var url = "/my/app/url2";
var some_url = "/my/app/url";
var row_count = row['available_count'];
var dataContent = '<a href=\''+some_url+'\'>'+NYC+'</a> <a href=\''+some_url+'\'>'+LA+'</a>';
var data = '<td> <div class="' + another_class + ' item-count-div" style="background-color:'+ color + ';" data-url="' + url + '" data-toggle="popover" data-content="'+dataContent+'" >' + row_count + '</div></td>';
Upvotes: 1
Reputation: 1012
If you're using newer versions of JS you could use a string template literal, like this:
const data = `<a href="${var1}">${var2}</a>`
Another approach is to use an array and the join function, like this:
const parts = ['<a href="', var1, '">", var2, '</a>'];
const data = parts.join('');
Upvotes: 0
Reputation: 87
data = '<td> <div class="' + another_class + 'item-count-div" style="background-color:'
+ color + ';"' + ' data-url="'+url+'" data-toggle="popover" data-content="<a
href="'+url+'">NYC</a> <a href="'+url+'">LA</a>" >' + row_count + '</div></td>';
Upvotes: 0