Building string with javascript - javascript

I have the following Problem:
I'm trying to build a simple string like that:
for(var x in classicde) {
specificWines += "<li><a onClick='displayWine(" + "'GV'" + ")'>" + classicde[x] + "</a></li>";
}
Then I insert this string in the DOM structure with:
var list = document.getElementById("leftmenu-list");
list.innerHTML = specificWines;
The result is the following(something like that i have shortened it):
<ul id="leftmenu-list">
<li><a onclick="displayWine(" gv')'>Classic1</a></li>
</ul>
So there is a problem within the onclick event and i am not able to find the issue.

Your quotes are wrong around 'displayWine(" + "'GV'" + ")' it should be 'displayWine(" + "\"GV\"" + ")' so the single quotes contains double quotes and do not break the attribute on render. \ is used to escape the quote so it doesn't break the JS code.
for(var x in classicde) {
specificWines += "<li><a onClick='displayWine(" + "\"GV\"" + ")'>" + classicde[x] + "</a></li>";
}
Otherwise as you see you end up with the single quote breaking the attribute. If you pass a string inside a string you need to make sure you use different quotes.
This should now render as
<li><a onclick='displayWine("gv")'>Classic1</a></li>

Related

js: can I assign a class or an id to an html-element that's part of a variable definition?

NOTE: My knowledge of programming is scant.
I've got this line of code somewhere:
var item = "<h3>" + '' + postTitle + " </h3> <p>" + postContent + "</p>";
postUrl , postTitle and PostContent have previously been declared.
I'd like to wrap it all up inside a <div> tag that has some class or id assigned to it, as in...
var item = "<div id="special"> <h3>" + '' + postTitle + " </h3> <p>" + postContent + "</p> </div>";
But that doesn't seem to work.
Is it because of the quotations getting messed up or is it the wrong way to go altogether?
You have two options:
Escaping the " quotes inside your string literal, like this: "<div id=\"special\"> <h3>"
Or using single quotes ' for either the outer string or inner one (you have the choice), like this: '<div id="special"> <h3>' or "<div id='special'> <h3>"
I personally prefer '<div id="special"> <h3>' because the generated HTML will contain the " quotes (which is the HTML standard) while keeping the JavaScript more readable and maintainable (compared to using escaped quotes)

Converting String to HTML - string to " a href" element

Hello I am having some trouble getting some HTML links to add to my HTML page. I have tried searching around but nothing has helped thus far.
My page will initially load a snippet:
<div style="display: inline-block; color: rgb(0, 255, 144)">Roster: </div>
<span id="teamRoster"></span>
<br />
Which appears like Roster: in the View
Right now my snippet has been modified to add names:
var rosterListings = "";
for (var i = 0; i < teamRoster.length; i++) {
rosterListings = rosterListings + teamRoster[i] + ", ";
}
$("#teamRoster").text(rosterListings);
Which will update my View to Roster: John, Frank, Susan, ect..
However, I am trying to now add <a href> tag's around each person and turn them all into actual links. My attempt looks like this
var rosterListings = "";
for (var i = 0; i < teamRoster.length; i++) {
rosterListings = rosterListings + " <a href='" + idList[i] + "'>" + teamRoster[i] + "</a>,";
}
$("#teamRoster").text(rosterListings);
which displays as
Roster: <a href='#'>John</a>, <a href='#'>Frank</a>, ect..
I understand why this occurring since I am setting actual text/strings, but is there a way to convert this string into HTML elements? I have tried a few $.parseHTML code snippets that I found from Googling but I must be implementing them all wrong.. :(
Any help appreciated, Thank you!
Well, solution is quite obvious
Just replace
$("#teamRoster").text(rosterListings);
With:
$("#teamRoster").html(rosterListings);
Because if you use it as a text then it will treat it as the text and if you write html then it will treat it as a html
The problem is that you're using .text(), which will insert only text into the span, as seen here.
You need to use .html() if you want what is inserted to actually render as HTML.
So, try this:
$("#teamRoster").html(rosterListings);
Demo
Also note that the way you've set up your for loop causes an extra comma to be placed at the end of the list; I've fixed that here by checking whether it's the last element:
if (i !== teamRoster.length - 1) {
rosterListings = rosterListings + " <a href='" + idList[i] + "'>" + teamRoster[i] + "</a>,";
} else {
rosterListings = rosterListings + " and <a href='" + idList[i] + "'>" + teamRoster[i] + "</a>.";
}
As Just code points out, you want to use the html method, not the text method. html() is jQuery's wrapper for innerHTML, which injects the string as html.
Here is a jsFiddle showing the difference:
http://jsfiddle.net/89nxt/
$("#teamRosterHtml").html("<a href='#'>John</a> <a href='#'>Frank</a>");
$("#teamRosterText").text("<a href='#'>John</a> <a href='#'>Frank</a>");

Breaking a string into multiple lines inside a javascript code

I am trying to format (beautify, tidy, clear up.. you name it) a snippet of HTML inside my javascript code or, in other words, spread it out on multiple lines rather than having it written on one line so it can be read easily.
Basically, it's a piece of html code that I am trying to append to the page by calling the jQuery's .append(); method.
And here's what I am trying to do:
$('.videos').append('<li>
<span>' + count + '</span> -
<a href="' + vList[i].player + '">
<span class="title">' + videoTitle + '</span>
</a>
</li>');
Appearantly, it won't work that way. I am getting Uncaught SyntaxError: Unexpected token >
When It is written as follows, everything works fine.
$('.videos').append('<li><span>' + count + '</span> - <span class="title">' + videoTitle + '</span></li>');
It's kind of weird that when I tried to do the exact thing here,
var albumURL = API + '/video.get?=owner_id=' + userID +
'&album_id=' + aList[i].album_id +
'&access_token=' + accessToken;
I had no problem at all.
I know this issue is not that big of a deal but I am trying to get around with it just for the sake of simplicity.
Any suggestions?
If you have a multiline string, you need to use the multiline string syntax.
However, it's better to store your HTML in templates and not code :) That makes them more readable, more reusable and more maintainable.
What about something like - in your HTML:
<script type="text/template" id="videoTemplate">
<li>
<span>{{count}}</span>
<a href="{{videoURL}}">
<span class="title">{{videoTitle}}</span>
</a>
</li>
</script>
Then in JavaScript
var template = $("#videoTemplate").html();
$(".videos").append(template.replace("{{count}}",count).
replace("{{videoURL}}",vList[i].player).
replace("{{videoTitle}}",videoTitle));
That way, you get a clearer separation of the template you're using and your code. You can change the HTML independently and reuse it in other parts of code more easily.
The code does not have to even be aware of template changes and a designer can change the design without knowing JavaScript.
Of course, if you find yourself doing this often you can use a templating engine and not having a .replace chain.
ES2015 also introduces template strings which are also kind of nice and serve the same purpose in principle:
const videoTemplate = `<li>
<span>${count}</span>
<a href="${vList[i].player}">
<span class="title">${videoTitle}</span>
</a>
</li>`;
If you want to write a multiline string you should use the "\":
example:
$('.videos').append('<li> \
<span>' + count + '</span> - \
<a href="' + vList[i].player + '"> \
<span class="title">' + videoTitle + '</span> \
</a> \
</li>');
New answer:
With ES6 you can actually use string concatenation that is line-break insensible:
var html = `
<li>
${count}
</li>
`;
and the line breaks will not be a problem. Prior to ES6 I used mostly arrays and concat them. Its faster:
var html = [
'<li>',
count
'</li>'
].join('');
Old answer:
In javascript you cannot break lines without concatenating them with a + or using \. Try this:
$('.videos').append('<li>' +
'<span>' + count + '</span> - ' +
'<a href="' + vList[i].player + '">' +
'<span class="title">' + videoTitle + '</span>' +
'</a>' +
'</li>');
If you simply want to split rendered output onto new lines then append \n where you want the newline to appear, like this...
$('.videos').append('<li>\n<span>' + count + '</span> -\n\n<span class="title">' + videoTitle + '</span>\n\n</li>\n');
And if you want your JS to look nice you could try this, which will also ensure that your rendered HTML is indented.
var item = '';
item += '<li>\n';
item += ' <span>' + count + '</span> -\n';
item += ' <a href="' + vList[i].player + '">\n';
item += ' <span class="title">' + videoTitle + '</span>\n';
item += ' </a>\n';
item += '</li>\n';
$('.videos').append(item);
you can try like this
$('.videos').append( ['<li>',
'<span>' + count + '</span> - ' ,
'<a href="' + vList[i].player + '">' ,
'<span class="title">' + videoTitle + '</span>' ,
'</a>' ,
'</li>'].join('') );
From New Perspectives on HTML5, CSS, and JavaScript 6th Edition, Chapter 9 Getting Started with JavaScript:
"If you want to break a text string into several lines, you can indicate that the text string continues on the next line by using the following backslash \ character.
Example of proper line break:
      window.alert("Welcome \
      to Tulsa");
If you are rendering HTML using backticks and want to pass a variable inside it's very easy just add the backticks around the variable and concatenate it. let's take an eye on the below example
var x = 1;
$(wrapper).append(`
<div class="card">
<div class="card-body">
<h5 class="card-title">Plot `+ x +` </h5>
</div>
</div>
`);

Create a link with javascript within it

so I am trying to create a link within my page but for some reason it is getting disjointed the code is
data = data + "<li><a href='#' onclick='History.pushState({state:null},'article,"+rtndata[j].id+"','article'); return false;'>" + rtndata[j].title + "</a></li>";
rtndata[j].id is an id number and rtndata[j].title is a title both are being pulled from a db but when it renders in the browser it becomes
<a false;'="" return="" article,41','article');="" onclick="History.pushState({state:null}," href="#">Newsflash 5</a>
so what I to render is actually
<a href="#" onclick="History.pushState({state:null},'article,41','article'); return false;'>"Newsflash 5</a>;
Can anyone help me?
The value of the onclick attribute is enclosed within single quotes. Because of this, you have to either use " or " (only for values) if you have to use quotes inside the attribute.
Because your JavaScript string is enclosed within double quotes ("), the double quotes have to be escaped before they can be used: "....onclick='...\"....'....";.
To fix your code, I have decided to use double quotes (escaped) instead of single quotes:
data = data + "<li>" + rtndata[j].title + "</li>";
Detailled table:
JS string marker Attribute marker Valid attribute value markers
" \" ' "
" ' \" "
' " \' "
' \' " "

Blinking page title

I'm trying to get some notifications working for AJAXChat. To do this all I want to do is get the title of the page to blink until focused. To do this I'm using the jquery-titlealert plugin. The problem is the html that is generated for the onload event is generated inside a js file shown here
return '<div id="'
+ this.getMessageDocumentID(messageID)
+ '" class="'
+ rowClass
+ '">'
+ this.getDeletionLink(messageID, userID, userRole, channelID)
+ dateTime
+ '<span class="'
+ userClass
+ '"'
+ this.getChatListUserNameTitle(userID, userName, userRole, ip)
+ ' dir="'
+ this.baseDirection
+ '" onload="$.titleAlert('New Message');">'
+ userName
+ '</span>'
+ colon
+ this.replaceText(messageText)
+ '</div>';
return
When I use this, it breaks the page. If I replace ('New Message') with (New Message) the page loads again but the notification isn't working. I think this is because its displaying a Javascript function inside Javascript. Anyone see anything here I'm missing?
Have you tried escaping your quotes? I.e.:
+ '" onload="$.titleAlert(\'New Message\');">'
Any single quote (') inside a single quoted string (or double quote (") inside a double quoted string) needs a backslash (\) before it. See the MDN String Literals documentation for more information about strings and proper character escaping.
You need to escape the quotes.
Change this
'" onload="$.titleAlert('New Message');">'
to this
'" onload="$.titleAlert(\'New Message\');">'
Try escaping the apostraphe's correctly:
+ '" onload="$.titleAlert(\'New Message\');">'

Categories

Resources