Add quote in javascript generated links - javascript

How do i fix this link in javascript.
Link
Its missing single quotes around 'Business'
Javascript:
html += "<option value='javascript:clientGalleryLink(" + titleArray[x] + ")'>" + titleArray[x] + "</option>";

use \ to escape the quotes
html += "<option value='javascript:clientGalleryLink(\"" + titleArray[x] + "\")'>" + titleArray[x] + "</option>";

<a href='javascript:clientGalleryLink("Business")'>Link</a>
html += "<option value='javascript:clientGalleryLink(\"" + titleArray[x] + "\")'>" + titleArray[x] + "</option>";
Could you please try this one out.
Thanks.

Try this to escape the attribute quotes and thus giving you the single inner quotes like you show in your example.
html += "<option value=\"javascript:clientGalleryLink('" + titleArray[x] + "')\">" + titleArray[x] + "</option>";

Escaping problems like this is why it's best to avoid creating JavaScript-in-HTML dynamically in strings. The javascript: pseudo-URL scheme should also never be used.
Instead, consider an ‘unobtrusive scripting’ approach: move the data out of an embedded JS string and into normal attributes, such as class or, if the link corresponds to a particular element on the page, the href itself:
<a class="gallerylink" href="#Business">Link</a>
for (var i= document.links.length; i-->0;) {
if (document.links[i].className==='gallerylink') {
document.links[i].onclick= function() {
clientGalleryLink(this.hash.substring(1));
return false;
};
}
}
The second example:
html += "<option value='javascript:clientGalleryLink(" + titleArray[x] + ")'>" + titleArray[x] + "</option>";
is just a mess. Aside from the lack of \' quoting around the titleArray value, and the lack of HTML-escaping or JS-string-literal-escaping on the titleArrays (so if you have '"<& characters in the title you've got problems).
Are you expecting the script to get executed when the option is chosen just because you've put it in the value? It won't.
Better to use the DOM objects than trying to mess around inserting JavaScript inside HTML inside JavaScript inside HTML. For example, if you're looking for a select box that calls clientGalleryLink every time the selected option is changed:
<div id="PlaceWhereYouWantToPutTheSelectBox"></div>
<script type="text/javascript">
var s= document.createElement('select');
for (var i= 0; i<titleArray.length; i++) {
s.options[i]= new Option(titleArray[i], titleArray[i]);
}
s.onchange= function() {
clientGalleryLink(this.options[this.selectedIndex].value);
};
document.getElementById('PlaceWhereYouWantToPutTheSelectBox').appendChild(s);
</script>
No ugly escaping necessary, no cross-site-scripting security holes.

add slashes:
\"" + titleArray[x] + "\"

Related

How to Prevent TD from ending up on a new line?

I am dynamically creating a table through Javascript and I DO want the table to continue off the right side of the page. Doing this manually lets the table continue off, but once I feed this into a for loop the <td>s wrap into a second line in the rendered HTML, creating two or more table rows when they reach the end of the page.
<div id="panelindex" style="overflow:scroll;text-align:center;">
<table border="0">
<tr></tr>
</table>
</div>
This is inside a table of its own (no style formatting). Then the Javascript:
var q = Math.floor((1/numpanels)*500);
if(q>50) q=50;
panelindex.innerHTML = "<table border='0'><tr>"
for(i=0; i<numpanels; i=i+1)
{
panelindex.innerHTML = panelindex.innerHTML + "<td><div id='panel" + i + "' onclick='jumppage(" + i + ")' style='float:left;text-align:center;margin:8px;border-width:3;border-color:white;border-style:none;'><a href='#" + i + "'><img src='thumbnails.php?image=blowem" + zeroFill(i,2) + ".gif&GIF&tw=128&th=128&quality=" + q + "'>\n" +
"<br />" + i + "</a></div></td>\n";
}
panelindex.innerHTML = panelindex.innerHTML + "</tr></table>"
You may notice that there is a <div> in the <td> and that is so I can apply a border marking the panel. Without the <div> it seems I cannot do that, and there are some other undesired effects. Any ideas what I can do so that all the <td>s end up on one line rather than split to a new line?
Example of what I want: http://edwardleuf.org/comics/jwb/009-conmet
What is happening: https://jsfiddle.net/w4uh0a3j/7/
Click the Show link.
innerHTML does not hold the string value you assign to it.
It parses the value as HTML, creates a DOM from it, inserts it into the document and then, when you read it back, it converts that DOM back into HTML.
This means that the string you assign is subject to error recovery and normalisation. In particular, the end tags you omitted are fixed.
panelindex.innerHTML = "<table border='0'><tr>"
console.log(panelindex.innerHTML);
<div id="panelindex" style="overflow:scroll;text-align:center;">
<table border="0"><tr>
</tr></table>
</div>
So when you start appending more data to it:
panelindex.innerHTML = panelindex.innerHTML + "<td>etc etc
You end up with:
<table border="0"><tbody><tr></tr></tbody></table><td>etc etc
Store your data in a regular variable. Only assign it to .innerHTML once you have the complete HTML finished.
A better approach then that would be to forget about trying to build HTML by mashing strings together (which is error prone, especially once you start dealing with characters that need escaping in HTML) and use DOM (createElement, appendChild, etc) instead.
OK,here is fixed html and js code. It seems like innerHTML fixes missing closing when updating html before all the code is building the rest of innerHTML. This code works :
<div id="panelindex" style="overflow:scroll;text-align:center;">
</div>
and js code :
var numpanels = 100;
var q = Math.floor((1/numpanels)*500);
if(q>50) q=50;
panelindex.innerHTML = "<table border='0'><tr>";
var html = "<table border='0'><tr>";
for(i=0; i<numpanels; i=i+1) {
html += "<td><div id='panel" + i + "' onclick='jumppage(" + i + ")' style='float:left;text-align:center;margin:8px;border-width:3;border-color:white;border-style:none;'><a href='#" + i + "'><img src='thumbnails.php?image=blowem" + ".gif&GIF&tw=128&th=128&quality=" + q + "'>\n" +
"<br />" + i + "</a></div></td>";
}
html += "</tr></table>";
document.getElementById("panelindex").innerHTML = html;

Dynamically add array contents as new elements - JQuery

edit: Problem solved! I was modifying the page before it was loaded so the script didn't actually do anything. I fixed it now and it works. Thanks for the help, I'll have to chalk this one up to being new to jQuery and it's weirdness.
Long story short I'm trying to make a webpage that dynamically takes Article titles, thumbnail images, descriptions, and links to them, and creates a nicely formatted list on the page. I'm trying to accomplish this in jQuery and HTML5.
Here is the sample data that I'll be using to dynamically populate the page. For now formatting isn't important as I can do that later after it works at all.
<script>
var newsTitles = ["If It Ain't Broke, Fix It Anyways"];
var newsPics = ["images/thumbnail_small.png"];
var newsDescs = ["August 14th 2015<br/><b>If It Ain't Broke</b><br/>Author: Gill Yurick<br/><br/> Sometimes, a solution isn't the only one. So how do we justify changes to systems that don't need to be fixed or changed? I explore various systems from other successful card games and how their approaches to issues (be they successes or failures in the eyes of the deisgners) can help us create EC."];
var newsLinks = ["it_aint_broke-gill_popson.html"];
var newsIndex = 0;
var newsMax = 1;
The section of code where I'm trying to use the contents of the arrays above to dynamically fill elements.
<td style="height:500px;width:480px;background-color:#FFF7D7;padding:20px" colspan=2 id="article">
<h1>Articles</h1>
<!-- the column for each news peice add an element with the thumbnail, the title and teh desc -->
<script>
for(i = 0; i < newsMax; i++) {
$("#articleList").append("<h3 href="" newsLinks[i] + "">" + newsTitles[i] + "</h3>", "<img src=""newsPics[i] + "">","<p>" + newsDesc[i] + "</p>", ); $("div").append("hello");
}
</script>
<div id="articleList">
HELLO
</div>
</td>
Here is what it ends up looking like, I can post more info if needed as I am aware this may not be clear enough to fully explain my problem but I am unable to determine that. Thank you in advance.
try this
for(i = 0; i < newsMax; i++) {
$("#articleList").append("<h3 href=""+ newsLinks[i] + "">" + newsTitles[i] + "</h3>, <img src=""+newsPics[i] + "">, <p>" + newsDescs[i] + "</p>" ); $("div").append("hello");
}
Concatation issue + typo for newsDescs
The following string is invalid html and is missing a +
"<h3 href="" newsLinks[i] + "">"
You need to use proper quotes for html attributes, not &quote;
Try
"<h3 href='" + newsLinks[i] + "'>"
OR
"<h3 href=\"" + newsLinks[i] + "\">" // `\` used to escape same type quote
Personally I prefer opening/closing html strings with single quotes but either will work
Note tht you should be getting a syntax error thrown in dev tools console which would have helped you locate problems
for(i = 0; i < newsMax; i++) {
$("#articleList").append("<h3 href='" + newsLinks[i] + "'>" + newsTitles[i] + "</h3>");
$("#articleList").append("<img src='" + newsPics[i] + "'>","<p>" + newsDesc[i] + "</p>" );
}

Parentheses in string of javascript function call

I have a loop that creates links with a javascript function call in the onClick events and uses the text returned from a database as one of the parameters. My issues I am having is that sometimes this text being returned has parenthesis in them which is causing a syntax error in my code.
Example:
code:
formResults += "<a onclick='openForm(" + this.displayText + "," + this.ID + ");'>" + this.displayText + "</a>";
HTMLDisplay:
<a onclick="openForm(Example Form (Example Form 1) Application Instructions ,1108);">Example Form (Example Form 1) Application Instructions </a>
as you can see the name of the form contains a set of parenthesis. Is there anyway I can include these? The reason I need to is because the function points to another system that uses the ID and displayText in order to render the proper form.
thank you
The parenthesis aren't the problem, it's the lack of quotes inside the function.
formResults += "<a onclick='openForm(\'" + this.displayText + "," + this.ID + "\');'>" + this.displayText + "</a>";
This below snippet (from yours)
`openForm(Example Form...`)
Will throw an error because it's looking for variables Example and so on, quote that string!
I strongly suggest
code:
formResults += '<a class="openForm" data-text="'+this.displayText + '" id="'+this.ID + '">' + this.displayText + '</a>';
HTMLDisplay:
<a class="openForm" data-text="Example Form (Example Form 1) Application Instructions" id="1108">Example Form (Example Form 1) Application Instructions </a>
jQuery:
$(function() {
$(".openForm").on("click",function(e) {
e.preventDefault();
openForm($(this).data("text"),this.id);
});
});

Javascript creating a li element and assigning text to data-attribute is being truncated

In javascript I am creating a li element as per below which contains only the problem I am seeing.
The data-videoUrl is showing the full url, so all good there.
The issue is the entry.link and entry.title, while debugging, I verified the strings are within quotes. i.e. "This is a pod cast." The data-videoTitle and data-videoDesciption are being truncated though. i.e. "This" will show from the previous example.
I'm not sure what is occuring in the latter two data assignments as I've verified the text is not double quoted etc. What is occuring with the html5 data elements? I can provide a more complete example if needed.
var podItem = document.createElement("li");
podItem.innerHTML = entry.title
+ "<a data-videoUrl=" + entry.link + " "
+ "data-videoTitle=" + entry.title + " "
+ "data-videoDescription=" + entry.contentSnippet + " "
+ "</a>";
document.getElementById("podCastList").innerHTML += podItem.innerHTML;
Here is a the html being generated.
<a data-videourl="http://rss.cnn.com/~r/services/podcasting/studentnews/rss/~3/d3y4Nh_yiZQ/orig-sn-060614.cnn.m4v" data-videotitle="CNN" student="" news="" -="" june="" 6,="" 2014="" data-videodescription="For" our="" last="" show="" of="" the="" 2013-2014="" school="" year,="" cnn="" takes="" a="" look="" back,="" ahead,="" and="" at="" stories="" making="" ...="" <=""></a>
I'm sure there's something I'm not fully understanding. Why would the first data element get the text correctly, and the next two data elements break up the text as in: [data-videotitle="CNN" student="" news=""]. The text is a straight forward sentence quoted i.e. "CNN student news..."
Why would videoUrl work correctly and the other two not?
You need to add some quotes around the attributes...
podItem.innerHTML = entry.title
+ "<a data-videoUrl=\"" + entry.link + "\" "
+ "data-videoTitle=\"" + entry.title + "\" "
+ "data-videoDescription=\"" + entry.contentSnippet + "\" "
+ "</a>";
You'll also want to make sure you escape any quotes that are inside the attributes as well.

How can I concatenate multiline string in javascript?

There are lots of results for the correct syntax for appending <li>'s, however I am trying to find a solution where +this['name']+ values are included in the <li>'s. firebug is displaying 'SyntaxError: unterminated string literal' and jslint is displaying 'Unclosed string'. I've tried many different variations of the placements of the commas but I haven't been able to get it to work.
$.each(data.result, function() {
$("ul").append("<li>Name: "+this['name']+"</li>
<li>Age: "+this['age']+"</li>
<li>Company: "+this['company']+"</li>
<br />");
});
Thank you.
you can escape end of line with backslash character \, like so:
$.each(data.result, function(){
$("ul").append("<li>Name: " + this['name'] + "</li> \
<li>Age: " + this['age'] + "</li> \
<li>Company: "+this['company']+"</li> \
<br />");
});
This is due to the fact that Javascript automatically insert semi-columns sometime on line end. And in this case, you string weren't close. Another solution is to close each string on each line, and using + to concat them all.
$.each(data.result, function(){
$("ul").append("<li>Name: " + this['name'] + "</li>" +
"<li>Age: " + this['age'] + "</li>" +
"<li>Company: "+this['company']+"</li>" +
"<br />");
});
(Unrelated, but you <br/> aren't allowed inside a <ul> element)
This should be much faster
li = '';
$.each(data.result, function(){
li += "<li>Name: " + this['name'] + "</li>" +
"<li>Age: " + this['age'] + "</li>" +
"<li>Company: "+this['company']+"</li>" +
"<br />"; // could remove this and use css
});
$("ul").append(li);
See http://net.tutsplus.com/tutorials/javascript-ajax/10-ways-to-instantly-increase-your-jquery-performance/
You actually don't want to concatenate this at all! Consider for a moment what will happen to variable data that contains HTML or HTML-like data. Using your method, it will be parsed as such, possibly breaking things and even opening you up to XSS attack methods.
You're already using jQuery, so the proper way is easy:
$('ul').append(
$('<li/>').text('Name: ' + this.name),
$('<li/>').text('Age: ' + this.age),
// etc.
);
(Note: I believe .append() allows as many parameters as you give it. If not, try using an array of elements as you append.)

Categories