How to pass string in Javascript function dynamically - javascript

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?

Related

Missing ) after argument but only for a long string

I am using JavaScript to fill a <div> tag with other <div>s. It has been working until I changed an identifier used inside a onclick event. The old identifier (index) was just a small number from 0-1000, but the new identifier (id) is a uuid.v4() generated string that looks like this:
f5ec8170-e75c-4a93-9997-1a683b7d2e00
I have the exact same code for index and the id. But whenever I click on the button which is suppose to activate the function call with the id as an argument it gives me:
Missing ) after argument
Which does not happen when I click on the button which does the same thing with index as an argument instead of id.
My code:
var id = messages[i].id;
var index = 0;
var newElement =
'<div class="fullMessage" id="fullRightMessage' + i + '">'+
'<h6 class="textMessage">' + messages[i].comment + '</h6>' +
'<button class="likeButtonMessage" onclick="likeClicked(right, ' + index + ', 1);">LIKE</button>' +
'<button class="dislikeButtonMessage" onclick="likeClicked(right, ' + id + ', -1);">DIS</button>' +
'<h4 id="scoreright' + i + '" class="messageScore">' + messages[i].score + '</h4>' +
'</div>'
You do not enclose the uuid with quotation marks. Before it worked because your id was a clean integer which doesn't need them.
Exchange the line with id to
'<button class="dislikeButtonMessage" onclick="likeClicked(right, \'' + id + '\', -1);">DIS</button>' +
Your previous ID was interpreted as an int, which is the reason why it worked.
Your new ID is a string, requiring you to enclose it in quotation marks:
onclick="likeClicked(right, \'' + id + '\', -1);"
This is because this is not valid code:
likeClicked(right, f5ec8170-e75c-4a93-9997-1a683b7d2e00, -1)

Invalid or unexpected token with multiline string

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).

Trying to escape quotes in a href tag

I have the following line of code,
$("#busdata").append("<div>" + data.response.results[i].webUrl + "</div>");
I essentially want the "data.response.results[i].webUrl" to replace the url string, but I'm not quite sure how to escape the quotes properly.
You can escape quotes by replacing them with \"
or just use single quotes - '
So "<div><a href="url">" becomes
"<div><a href=\"url\">" or "<div><a href='url'>"
a single quote ' and a string concatenator +
$("#busdata").append("<div><a href='"+ data.response.results[i].webUrl +"'>" + data.response.results[i].webUrl + "</a></div>");
Your syntax is wrong. You need to escape quotes. Change your <a href="url"> to <a href=\"url\"> like this:
$("#busdata").append("<div>" + data.response.results[i].webUrl + "</div>");
Or if you feel that's a bit tough, you can exchange the quotes, ' for ":
$("#busdata").append('<div>' + data.response.results[i].webUrl + "</div>");
Else, if you are trying to add the URL from the response:
$("#busdata").append("<div>" + data.response.results[i].webUrl + "</div>");
if url is a variable
$("#busdata").append("<div><a href='" + url +"'>" + data.response.results[i].webUrl + "</a></div>");
and if you want to write by yourself
$("#busdata").append("<div><a href='url'>" + data.response.results[i].webUrl + "</a></div>");
You can store it in variable instead :
var url = data.response.results[i].webUrl;
$("#busdata").append("<div>" + url + "</div>");
Hope this helps.
Simply do it following my example:
var a = $('<a />', {
href: 'url here',
text: 'text here'
}); $('body').append(a);
You could do this :
$("#busdata").append("<div><a href='"+data.response.results[i].webUrl +"'>" + data.response.results[i].webUrl + "</a></div>");
Since you are using double quotes for the string to append, you can use single quotes around the variable in the href attribute and then add that variable.
This is most easily achieved by not building HTML by smashing strings together in the first place.
$("#busdata").append(
$("<div />").append(
$("<a />").attr("href", data.response.results[i].webUrl)
)
);
Escaping quotes is not necessary
$("#busdata")
.append("<div><a href="
+ data.response.results[i].webUrl
+ ">"
+ data.response.results[i].webUrl
+ "</a></div>"
);

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>';
}

Passed URL string not interpret as a string

I read quite some articles and tried some approaches, but couldn't get it to work.
htmlCode += '<button id="' + addButtonId + '" title="' + addButtonTitle + '" class="button" onclick="getProductUrl(' + url + '); return false;"><span><span>' + addWithButonTitle + '</span></span></button>';
and the function itself:
getProductUrl: function(url) {
return setLocation('\'' + decodeURIComponent(url) + document.getElementById('qty_field').value + '\'');
},
Apparently, the string value of the url is not treated as a string. I get an error of missing bracket here: getProductUrl(http:^//...rest of the url. Of course the problem is not in the bracket, but in the fact that the // are treated as a start of a comment.
So the thing that I have to do is to pass this url string value CORRECTLY as a string.
I tried first decoding and then passing (because decodeURIComponent(url) should return string. Also I tried String(url) and url + "". Also somehow escaping the special characters: url.replace('/','\/') or even the /g thingy, which didn't work at all.
So, all these approaches were unsuccessful. I would really appreciate a hint or a solution here.
Try this one
onclick="getProductUrl('" + url + "');"
For your updated line of code:
htmlCode += '<button id="' + addButtonId + '" title="' + addButtonTitle + '" class="button" onclick="getProductUrl(\'' + url + '\'); return false;"><span><span>' + addWithButonTitle + '</span></span></button>';

Categories