Javascript to build HTML - javascript

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 + '\')"

Related

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

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

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

escaping double and single quotes in jquery tooltip

I am using a dynamic jquery carousel to show thumbnail images in the home page....The carousel is working fine...and i want to add a tooltip to each image....for this i am using jquery tooltip....on hover tooltip should display the original image,uploaded by and so on...
The javascript that adds the tooltip to each image is as follows...
function mycarousel_getItemHTML(url)
{
var url= url.split(",");
return '<img src="' + url[0] + '" width="75" height="75" alt="" />';
};
url[5]=original img src
url[1]=title
url[6]=category name
url[2]=no of views
url[3]=uploaded by
url[0]=thumbnail img source
the above javascript gives me the following error
missing ) after argument list
how can i escape single and double quote properly...Please help me...-
I think the onmouseover portion is wrong, and you want:
onmouseover="Tip(\'<img src=\\\''+url[5]+'\\\' /><br/><b>'+url[1]+'</b><br />Category:'+url[6]+'<br/>Views:'+url[2]+'<br/>Uploaded by:'+url[3]+'\')"
Let me know if that doesn't work - my head's hurting from trying to be a JavaScript interpreter. I think that's on the right lines though.
p.s. I fixed your <img> tag - I think in general <img> tags should be self-closing <img... />, not <img...></img>.
Assuming the HTML " entity gets interpreted properly (and reformatting so people can see what's going on.):
function mycarousel_getItemHTML(url)
{
var url= url.split(",");
// wrapping attributes in double-quotes, so use double-quote
// entity within attribute values:
return '<a href="' + url[4] + '" ' +
'onmouseover="Tip(\'<img src="' + url[5]+'"/><br/>' +
'<b>' + url[1] + '</b><br />' +
'Category:' + url[6] + '<br/>' +
'Views:' + url[2] + '<br/>' +
'Uploaded by:' + url[3] + '\')" ' +
'onmouseout="UnTip()">';
};
Note: you should probably entity-encode all the < to < inside the onmouseover attribute too. That might leave less scope for browsers to bork the tooltip

Categories