Invalid or unexpected token with multiline string - javascript

I'm trying to return an HTML string out from a function in my JavaScript code, but on the console I get the error "Uncaught syntax error: invalid or unexpected token" with the following code
function formatPrize (prize) {
return (
/*Unexpected token here*/ '<div class = "wrapper">
<div class = "card radius shadowDepth1">
<div class ="card__image border-tlr-radius">
<img src = "admin/"'+prize.sponsorLogo+'"> alt = "image" class = "border-tlr-radius">
</div>
<div class = "card_content card_padding">
<div class = "card_meta">
<h3>"'+prize.name+'"</h3>
</div>
<article class = "card__article">
Test message
</article>
</div>
</div>
</div>'
);
}
I basically replaced some other piece of code that was here before and worked:
"<tr>" +
"<td>" + prize.name + "</td>" +
"<td>$" + prize.value + "</td>" +
"<td>" + prize.description + "</td>" +
"</tr>"
Did I did something wrong when replacing that? How can I fix it?

The problem is that single quotes and double quotes cannot create multiline strings in JavaScript.
As an alternative, either make each line a separate string and concatenate them, or do the following:
To have a multiline string, you need to replace the single quotes (') with a backtick (`) in JavaScript — this may be causing the error.
As #noazark pointed out, this may have limited compatibility because it came with ES6, which is still relatively new.
You can also escape the newline with a backslash at the end of each line.
See this SO answer for more details on the previous two methods.

You have to escape the newline character (with \) or concatenate multiple lines (both shown below).
function formatPrize (prize) {
return '<div class = "wrapper"> \
<div class = "card radius shadowDepth1"> \
<div class ="card__image border-tlr-radius"> \
<img src = "admin/"'+prize.sponsorLogo+'"> alt = "image" class = "border-tlr-radius"> \
</div>' +
'<div class = "card_content card_padding">\n' +
'<div class = "card_meta">\n' +
'<h3>"'+prize.name+'"</h3>\n' +
'</div>\n' +
' \n' +
'<article class = "card__article"> \
Test message \
</article> \
</div> \
</div> \
</div>';
}

Unfortunately most browsers do not support multi-line strings in javascript. You can do something like this though:
[
"<tr>",
"<td>" + prize.name + "</td>",
"<td>$" + prize.value + "</td>",
"<td>" + prize.description + "</td>",
"</tr>"
].join('')
Edit
The original version you provided works because the + operator looks for the next string, and since JavaScript is not whitespace sensitive, you can place it on the next line without any issues. So specifically your change was replacing the addition sign (string concatenation) with a multi-line string (which is not supported).

Related

How to pass JavaScript arguments using inner HTML

I am new to JavaScript and I am currently stuck on an issue. Basically, I using an API to search for anime, get the html image, synopsis, and name and put them in a table. That works fine. What I am trying to do is add an onlick for each name in the table to perform a function using the name of the anime as an argument. I have tried using "\'", the escape character, and it didn't work. Here is my code for each row:
nameAndSynopsis.innerHTML = "<table style='border: 1px solid black'><tr><td style='color:blue' onclick='getEpisodes(\'" + anime_name + "\')'>" + anime_name + "</td></tr><br><br><br><tr><td>" + anime_synopsis + "</td></tr></table>";`
When I run my code, the console says Unexpected end of input and here are the results from the source tab when I use inspect on my web page
`getEpisodes(`
Any help would be greatly appreciated.
If you have to use quotes, here how you will do it:
var functionname = "getEpisodes('" + anime_name + "')";
nameAndSynopsis.innerHTML = '<table style="border: 1px solid black"><tr><td style="color:blue" onclick="' +functionname+ '">' + anime_name + '</td></tr><br><br><br><tr><td>' + anime_synopsis + '</td></tr></table>';
I have added functionname in separate line to simply it. It can be done in single line as well.
<div id="nameAndSynopsis"></div>
<script>
function getEpisodes(something) {
console.log("ok.........");
}
var nameAndSynopsis = document.getElementById("nameAndSynopsis");
var anime_name = "anime_name";
var anime_synopsis = "anime_synopsis";
var functionname = "getEpisodes('" + anime_name + "')";
nameAndSynopsis.innerHTML = '<table style="border: 1px solid black"><tr><td style="color:blue" onclick="' + functionname + '">' + anime_name + '</td></tr><br><br><br><tr><td>' + anime_synopsis + '</td></tr></table>';
</script>
Try using template literals instead of all the quotes like this.
nameAndSynopsis.innerHTML = `<table style='border: 1px solid black'><tr><td style='color:blue' onclick=getEpisodes(${anime_name})> ${anime_name} </td></tr><br><br><br><tr><td>${anime_synopsis}</td></tr></table>`
You are using single-quote around the attribute value onclick=' <-- '
Then you are escaping the single quote, so it comes out like this ..
onclick='getEpisodes('yourAnimeName')'
Which sets your onclick attribute to getEpisodes(
This may not make sense and you may be asking, how does it end up like that, didn't i just ESCAPE those quotes?
Well, yes and no, you escaped them in the current javascript context. But since that is then inserted into the DOM as html, the html parser won't see those single-quotes as being escaped.
Try using double-quotes instead.
onclick='getEpisodes(\""+anime_name+"\")'
or
onclick=\"getEpisodes('"+anime_name+"')\"
Your code is ending with an unkown string there, right at the end
</table>";` <---- remove this last string
It should be ending like this
</table>";

How to pass string in Javascript function dynamically

I have a javascript function like this
function doIt(link) {
alert(link);
}
And i call this function in below given JS code, where i am creating an a tag and appending it to my html page on runtime:
jQuery.each(data, function (i, val) {
var card = '<a href="Views/NewsDetail.html" onclick=" doIt(' + val.Img + '); "> \
<div class=" card"> \
<img src='+ val.Img + ' /> \
<p>'+ val.Title + '</p> \
</div> \
</a>';
document.getElementById('News').innerHTML += card;
});
Say for example our val.Img = 'abcd'
When i click the a tag it calls doIt(abcd), but i want to call doIt('abcd') passing it as string.
Is there any workaround for this.
You need to escape quotes like
var card ='<a href="Views/NewsDetail.html" onclick="doIt(\'' + val.Img + '\'); "> \
//^ ^
As per your current implementation the argument abcd is treated as variable thus you must be getting undefined
You can do this one:
var card='';
The below HTML string already used both quotes till the characters doIt(. So any string type values inside the quotes, must be escaped using any of the quote-character.
var card = '<a href="Views/NewsDetail.html" onclick=" doIt(' + val.Img + '); ">'
to [added quote escape character \"]
var card = '<a href="Views/NewsDetail.html" onclick=" doIt(\"' + val.Img + '\"); ">'
Yet another option:
var doItAndRedirect=function(val){
//do stuff with val here
window.location = "Views/NewsDetail.html";
}
jQuery.each(data, function (i, val) {
var card = '<a href="javascript:doItAndRedirect(\''+ val +'\')">'+
'<div class=" card">' +
'<img src='+ val.Img + ' />' +
'<p>'+ val.Title + '</p>' +
'</div>'+
'</a>';
document.getElementById('News').innerHTML += card;
});
It is already a string it just doesn't display '' on alert but at the background it is string only.
doIt("' + val.Img + '");
should do it, but if you have, e.g, " inside val.Img you need to quote those: How do I add slashes to a string in Javascript?

How to form variable string with HTML and corresponding quotations

I'm building a string of text using HTML and variables from a JSON file. The issue is that the quotation marks from the HTML are conflicting with the quotations from the js expression - specifically when I'm trying to build a URL from a string of a URL partial + a json variable.
Here's my code. Any help?
output += '<li><span><a>' +
jobs[i].title +
'</a></span><span>' +
jobs[i].city +
'</span><span><a href='http://user.theresumator.com/apply/'' +
jobs[i].board_code +
'><button>More Info ›</button></a></span></li>';
}
My desired outcome is something like:
<li><span><a>Social Impact Strategist (Los Angeles or New York)</a></span><span></span><span><button>More Info ›</button></span></li>
Escape your quotes with \:
output += '<li><span><a>' +
jobs[i].title +
'</a></span><span>' +
jobs[i].city +
'</span><span><a href=\'http://user.theresumator.com/apply/' +
jobs[i].board_code +
'\'><button>More Info ›</button></a></span></li>';
}
or use double quotes ":
output += '<li><span><a>' +
jobs[i].title +
'</a></span><span>' +
jobs[i].city +
'</span><span><a href="http://user.theresumator.com/apply/' +
jobs[i].board_code +
'"><button>More Info ›</button></a></span></li>';
}
The 2nd one will match your desired outcome with double quotes perfectly.
Here's the working code! I broke it out on a separate line and add double quotes by themselves contained in single quote.
output += '<li><span><a>' +
jobs[i].title +
'</a></span><span>' +
jobs[i].city +
'</span><span><a href=' +
'"http://user.theresumator.com/apply/' +
jobs[i].board_code +
'"' +
'><button>More Info ›</button></a></span></li>';
}

Javascript to build HTML

this one may be simple but it has eluded me. I have Javascript code which builds elements in the DOM (using JSON from a server script). Some of the elements have "onclick" calls that I want to pass the ID variable to.
I cannot seem to get the onclick="downloadImg("' + d.data_id + '")" syntax right. What should it be. The code below does not work. Thanks.
temp_html = temp_html + '<img src="/link/to/img.png" onclick="downloadImg("' + d.data_id + '")">';
If you use the double quotations, you will close the previous one, so you create a conflict. So replace " with a single quotation + escape \' like this:
temp_html = temp_html + '<img src="/link/to/img.png" onclick="downloadImg(\'' + d.data_id + '\')">';
Your line should be:
temp_html = temp_html + '<img src="/link/to/img.png" onclick="downloadImg(\\"' + d.data_id + '\\")">';
You basically have many layers of quotes so the
double slash
creates a
\"
in the output that escapes the quote once it gets outputted to HTML
<img src="/link/to/img.png" onclick="downloadImg("' + d.data_id + '")">';
This will resolve to something like: <img src="/link/to/img.png" onclick="downloadImg("1")">
As you can see you have double quotes inside double quotes. Something like this should do it:
<img src="/link/to/img.png" onclick="downloadImg(\'' + d.data_id + '\')">
Change your double quotes to single quotes and escape them:
onclick="downloadImg(\'' + d.data_id + '\')"

Adding HTML code with Single Quotes inside jQuery

I am trying to add this HTML/JavaScript code into a jQuery variable. I've managed to insert double quotes by writing is with a backshlash \", however the same tactic didn't work for the single quotes:
ajaxData += '<div class=\"menu-item-' + $(this).attr('div') + 'onclick=\"alert('Jquery Function');\"></div>';
Specifically, this part onclick=\"alert('Jquery Function');
Anyone know how I can go around this?
See this, its beautiful:
ajaxData += '<div class="menu-item-' + $(this).attr('div') + ' onclick="alert(\'Jquery Function\');"></div>';
Dirty escape pheeww...Try this
ajaxData += '<div class="menu-item-' + $(this).attr('div') + 'onclick="alert(\'Jquery Function\');"></div>';
ajaxData += '<div class="menu-item-' + $(this).attr('div') + 'onclick="alert('Jquery Function');"></div>';
add escape \ for single quotes. if your string is within single quotes then you can use double quotes without escape but if using single quotes within single quote then you have to insert escape character
This is are you trying to do?
$var = "ajaxData += '<div class=\"menu-item-' + \$(this).attr('div') + '" onclick=\"alert(\'Jquery Function\');\"></div>';"

Categories