How do you escape characters when including a variable in a href, img attributes etc. This does'nt seem to work:
var myData = JSON.parse(jsonString2);
var $grouplist = $('#groups');
$.each(myData, function() {
$('<li><a href="'+ this.url + '"/><img src="'+ this.src + '" class="image0"/></a></li>').appendTo($grouplist);
});
}
Whole function above.
$('<li><a href=\"' + this.url + '\"</a></li>').appendTo($grouplist);
You don't need to. Create the element and set the attribute, then you don't need to worry about escaping anything, neither the quotation marks, not the attribute value:
$('<li>').append($('<a>', { href: this.url })).appendTo($grouplist);
Edit:
The code with the image element also:
$('<li>').append(
$('<a>', { href: this.url }).append(
$('<img>', { src: this.src, 'class': 'image0' })
)
).appendTo($grouplist);
You only need to escape when you have the same quotes. In your case this will work:
$('<li><a href="' + this.url + '"</a></li>').appendTo($grouplist);
Because the double quotes won't interfere with the single ones.
You don't need to escape the double quotes, because they are inside single quotes. Also, you didn't finish the opening a tag.
Check out window.escape. There is also encodeURIComponent, which is generally preferred if it is user-input.
As others pointed out, you don't need to escape your double quotes there. So try this:
$('<li></li>').appendTo($grouplist);
Or Guffa's approach:
$('<li>').append($('<a>', { href: encodeURIComponent(this.url) })).appendTo($grouplist);
Related
i have jquery code like this, but when i click image share, its not working.
am i wrong about typing single quote ?
onClick="window.plugins.socialsharing.share('+my_var+')"
var my_var="";
my_var="Hello World";
$('#info_detail').append('<table border="0"><tr><td><img src="favourite.png" onClick="
set_favorit('+employee.info_id+')"></td><td><img src="share.png" onClick="
window.plugins.socialsharing.share('+my_var+')"></td></tr></table>');
thank you
The issue is because my_var is a string, therefore you need to wrap it in escaped quotes in the output. The same may be true for the employee.info_id value too:
$('#info_detail').append('<table border="0"><tr><td><img src="favourite.png" onClick="
set_favorit(\'' + employee.info_id + '\')"></td><td><img src="share.png" onClick="
window.plugins.socialsharing.share(\'' + my_var + '\')"></td></tr></table>');
You should however note that on* event attributes are very outdated and should be removed in favour of unobtrusive event handlers instead, like this:
$('#info_detail').append('<table border="0"><tr><td><img src="favourite.png" data-info-id="' + employee.info_id + '" class="favorit" /></td><td><img src="share.png" data-share="' + my_var + '" class="share"></td></tr></table>');
$('#info_detail').on('click', '.favorit', function() {
set_favorit($(this).data('info-id'));
}).on('click', '.share', function() {
window.plugins.socialsharing.share($(this).data('share'));
});
Your onClick for the share image is rendering incorrectly.
onClick="window.plugins.socialsharing.share('+my_var+')"
with my_var = "Hello World" becomes
onClick="window.plugins.socialsharing.share(Hello World)"
This is not only invalid because of the space, but also because it isn't being passed into as a string as you may be assuming. This can be remedied by adding single quotes to my_var = "'Hello World'". You may also be better off adding click handlers outside the HTML itself.
var my_var="Hello World",
employee = 'demo';
$('#info_detail').append('<table border="0"><tr><td><img src="favourite.png" data-info-id="' + set_favorit(employee) + '" class="favorit" /></td><td><img src="share.png" data-share="' + myVar(my_var) + '" class="share"></td></tr></table>');
function set_favorit(a) {
console.log(a)
}
function myVar(b) {
console.log(b)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="info_detail"></div>
As I don't have that window function, I have added some custom functions. Kindly check.
Try removing both single quotes from the statement I tried running the code removing the quotes it worked on my end.
Here is the code.
var my_var="";
my_var="Hello World";
var employee = {
info_id: 10
}
$('#info_detail').append('<table border="1"><tr><td><img src="favourite.png" onClick="set_favorit('+employee.info_id+')"></td><td><img src="share.png" onClick="alert(my_var)"></td></tr></table>');
I am trying to replace quote (') with \' so as to escape escape quote or double quote in string
<ul id="list">
</ul>
<button id="sethrefbtn" onclick="setlink();">Set Link</button>
function setlink(){
var data = {
playerID : 102458,
playername: "Real Madrid's cristiano Ronalado"
}
listring= "<li><a href='SearchServlet?q=" + data.playername.replace(/'/g, "\'"); + "&playerid=" + data.playerID + "&page=1#pg0'>"+ data.playername +"</a></li>";
$("#list").append(listring);
}
Here is fiddle: fiddle
The desired output should be:
Real Madrid's cristiano Ronalado
Your problem is being caused by it being in an HTML attribute (so you need to convert it to an HTML character reference and not escape it). You should deal with that by using DOM instead of string mashing to build your HTML.
However, in this particular case, you are putting it in a URL, so you should be escaping it for URLs first.
You can do that with encodeURIComponent, but since you are building an entire query string and are using jQuery, you can use param instead.
function setlink() {
var data = {
playerid: 102458,
q: "Real Madrid's cristiano Ronalado",
page: 1
}
var url = "SearchServlet?" + $.param(data);
var li = $("<li />").append(
$("<a />").text(data.q).attr('href', url)
);
$("#list").append(li);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="list">
</ul>
<button id="sethrefbtn" onclick="setlink();">Set Link</button>
listring= "<li><a href='SearchServlet?q=" + data.playername.replace(/'/g, "\'") + "&playerid=" + data.playerID + "&page=1#pg0'>"+ data.playername +"</a></li>";
Just replace the above statement in the code .
There is a semicolon in the middle of the statement in your code.
I am generating dynamic HTML and want to pass an array to the calling function. The array is also being dynamically generated.
The contents of pinfoarray are somewhat like this "Ice Hockey","Junior Basketball","Ladies Soccer"
var theHost = "<a href='#someDialog' onclick='chnghost(' + pinfoarray + ');' data-toggle='modal' class='button'>Change</a>";
How can make it send the array to the calling function without an error.
How about making it like this:
var anchor = document.createElement('a');
anchor.href = '#someDialog';
anchor.setAttribute('data-toggle','modal');
anchor.className='button';
anchor.onclick = function(){
chnghost(pinfoarray);
}
You need to properly terminate the string and encode the parameter. You also need to guard against reserved characters in your data (escapeHtml).
var theHost = "<a href='#someDialog' onclick='chnghost(" + escapeHtml(JSON.stringify(pinfoarray)) + ");' data-toggle='modal' class='button'>Change</a>";
If you're using jQuery, you can implement escapeHtml like so:
function escapeHtml(text) {
return $("<div/>").text(text).html();
}
You need to close the string double quote to put a javascript variable:
var theHost = "<a href='#someDialog' onclick='chnghost('" + pinfoarray + "');' data-toggle='modal' class='button'>Change</a>";
Not sure how to write this the correct way. i can make it work but when i view source it looks like this
<img "="" "style="width:30%; height:30%;" src="correctsource"></img>
as you can see at the beggining of the image tag their is two extra quotes & a equal sign.
Here is my code
var img = $(this).attr('src');
//grab the visible div and the div with class edititable within it and append image
$(".open:visible").find('.edititable').append('<img src="' + img + '" "style="width:30%; height:30%;" ">');
Change to:
foo.append(
$("<img />", {
src: img,
style: "width: 30%; height: 30%"
})
);
It's easier to avoid mistakes with mismatched quotes this way, and generally improves readability too
Try this, you had too many double quotes in the string.
$(".open:visible").find('.edititable').append('<img src="' + img + '" style="width:30%; height:30%;">');
remove last double quotes then it will work.You added one extra .
that is write like
.................height:30%;">');
Close, your string simply was formatted incorrectly. You had an extra " infront of style. Tech you wrote it as
$(".open:visible").find('.edititable').text('<img src="' + img + ' " style="width:30%; height:30%;" ">');
Relevant fiddle: http://jsfiddle.net/6cLYf/
I have a Javascript / JQuery problem.
I get unterminated string literal when I use this code:
var newInfo = '<div><span class="testClass"><a title="edit" href="'+link+'">'+oldVal+'</a></span></div>';
If I delete the </div>
tag, it works... But I need this.
I am totally out of ideas.
Maybe you can help, thanks.
Escape your slashes.
var newInfo = '<div><span class="testClass"><a title="edit" href="' + link + '">' + oldVal + '<\/a><\/span><\/div>';
You could also just build your html as actual DOM elements instead of a string (which avoids a lot of pitfalls, including this one).
var div = $('<div />'),
span = $('<span />').addClass('testClass'),
a = $('<a />').text(oldVal).attr({
"href": link,
"title": "edit"
}),
newInfo = div.append(span.append(a));
Try to use
var newInfo = '<di'+'v><span class="testClass"><a title="edit" href="'+link+'">'+oldVal+'</a></span></di'+'v>';
Seperating the div tags helped me on a similar problem