syntax error jquery single quote - javascript

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

Related

Store html code to javascript variable

I have a problem when converting store html code to javascript variable, I know we can convert using converter tools, but I can't use this converter in my situation.
I am trying the following code
var t_cls="font-effect-anaglyph rotator";
var randompostsurl="www.allinworld99.blogspot.com";
var randompoststitle="Open Inspect Element And see the Code";
var default_script = "<script> document.write('<div><a class="+t_cls+" href=\"' + randompostsurl + '\" rel=\"nofollow\">' + randompoststitle + '<\/a><\/div>'); <\/script>\n";
$("#apnd").append(default_script);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div id="apnd"></div>
The above one will produce the following output
<a class="font-effect-anaglyph" rotator="" href="www.allinworld99.blogspot.com" rel="nofollow">Open Inspect Element And see the Code</a>
Why the rotator class will created as new attribute?
Because there are no quotes around the class attribute in the result. You need to add them, since you have a space in the attribute's value:
default_script = "<script> document.write('<div><a class=\""+t_cls+"\" href=\"' + randompostsurl + '\" rel=\"nofollow\">' + randompoststitle + '<\/a><\/div>');<\/script>\n";
// Here --------------------------------------------------------^^---------^^
Replace your default_script code
default_script = "<script> document.write('<div><a class='"+t_cls+"' href=\"' + randompostsurl + '\" rel=\"nofollow\">' + randompoststitle + '<\/a><\/div>');<\/script>\n";
As there are no quotes in class, it produce rotator as a new attribute. But you can achieve rotator as a class by the following way. i.e replacing single quotes with escape sequence.
<script>$(document).ready(function(){
var t_cls="font-effect-anaglyph rotator", randompostsurl="www.allinworld99.blogspot.com",
randompoststitle="Open Inspect Element And see the Code",
default_script = "document.write(\"<div><a class=\""+t_cls+"\" href=\"" + randompostsurl + "\" rel=\"nofollow\">\" + randompoststitle + \"<\/a><\/div>\");<\/script>\n";
$("#apnd").append(default_script);
});
</script>

Cannot Parse String via JavaScript function

I'm dynamically generate tables row (buttons) using JS- Ajax.when i parse a numeric value removeProduct function return the alert. but i cant get alert if i parse a String. can anyone help me to solve this problem
problem is in this line :
onclick='removeProduct( " + prcode + " )'
how to parse a String via function? (as a JavaScript String)
var single = alldata[i].split("##");
var rows = "";
var prcode = single[1];
rows += "<td><a class='btn' onclick='removeProduct( " + prcode + " )' href='#'><i class='fa fa-trash-o'></i></a></td></tr>";
$(rows).appendTo("#tblproductslist tbody");
Function :
function removeProduct(str) {
alert(str);
}
Thanks in advance!
Because you are trying to pass a string literal, so try to enclose the value in ""
onclick='removeProduct(\"" + prcode + "\")'
Since you are working with jquery, I would recommend you use event delegation to handle event and the data-api to store the data.
You need this:
rows += "<td><a class='btn' onclick='removeProduct( \"" + prcode + "\" )' href='#'><i class='fa fa-trash-o'></i></a></td></tr>";
If "prcode" is a string you must to quote it or it will be treated as (undefined) variable and will trigger an error.
Good luck!

Javascript to build HTML

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

Uncaught ReferenceError: function is not defined with onclick

I'm trying to make a userscript for a website to add custom emotes. However, I've been getting a lot of errors.
Here is the function:
function saveEmotes() {
removeLineBreaks();
EmoteNameLines = EmoteName.value.split("\n");
EmoteURLLines = EmoteURL.value.split("\n");
EmoteUsageLines = EmoteUsage.value.split("\n");
if (EmoteNameLines.length == EmoteURLLines.length && EmoteURLLines.length == EmoteUsageLines.length) {
for (i = 0; i < EmoteURLLines.length; i++) {
if (checkIMG(EmoteURLLines[i])) {
localStorage.setItem("nameEmotes", JSON.stringify(EmoteNameLines));
localStorage.setItem("urlEmotes", JSON.stringify(EmoteURLLines));
localStorage.setItem("usageEmotes", JSON.stringify(EmoteUsageLines));
if (i == 0) {
console.log(resetSlot());
}
emoteTab[2].innerHTML += '<span style="cursor:pointer;" onclick="appendEmote(\'' + EmoteUsageLines[i] + '\')"><img src="' + EmoteURLLines[i] + '" /></span>';
} else {
alert("The maximum emote(" + EmoteNameLines[i] + ") size is (36x36)");
}
}
} else {
alert("You have an unbalanced amount of emote parameters.");
}
}
The span tag's onclick calls this function:
function appendEmote(em) {
shoutdata.value += em;
}
Every time I click a button that has an onclick attribute, I get this error:
Uncaught ReferenceError: function is not defined.
Update
I tried using:
emoteTab[2].innerHTML += '<span style="cursor:pointer;" id="'+ EmoteNameLines[i] +'"><img src="' + EmoteURLLines[i] + '" /></span>';
document.getElementById(EmoteNameLines[i]).addEventListener("click", appendEmote(EmoteUsageLines[i]), false);
But I got an undefined error.
Here is the script.
I tried doing this to test if listeners work and they don't for me:
emoteTab[2].innerHTML = '<td class="trow1" width="12%" align="center"><a id="togglemenu" style="cursor: pointer;">Custom Icons</a></br><a style="cursor: pointer;" id="smilies" onclick=\'window.open("misc.php?action=smilies&popup=true&editor=clickableEditor","Smilies","scrollbars=yes, menubar=no,width=460,height=360,toolbar=no");\' original-title="">Smilies</a><br><a style="cursor: pointer;" onclick=\'window.open("shoutbox.php","Shoutbox","scrollbars=yes, menubar=no,width=825,height=449,toolbar=no");\' original-title="">Popup</a></td></br>';
document.getElementById("togglemenu").addEventListener("click", changedisplay,false);
Never use .onclick(), or similar attributes from a userscript! (It's also poor practice in a regular web page).
The reason is that userscripts operate in a sandbox ("isolated world"), and onclick operates in the target-page scope and cannot see any functions your script creates.
Always use addEventListener()Doc (or an equivalent library function, like jQuery .on()).
So instead of code like:
something.outerHTML += '<input onclick="resetEmotes()" id="btnsave" ...>'
You would use:
something.outerHTML += '<input id="btnsave" ...>'
document.getElementById ("btnsave").addEventListener ("click", resetEmotes, false);
For the loop, you can't pass data to an event listener like that See the doc. Plus every time you change innerHTML like that, you destroy the previous event listeners!
Without refactoring your code much, you can pass data with data attributes. So use code like this:
for (i = 0; i < EmoteURLLines.length; i++) {
if (checkIMG (EmoteURLLines[i])) {
localStorage.setItem ("nameEmotes", JSON.stringify (EmoteNameLines));
localStorage.setItem ("urlEmotes", JSON.stringify (EmoteURLLines));
localStorage.setItem ("usageEmotes", JSON.stringify (EmoteUsageLines));
if (i == 0) {
console.log (resetSlot ());
}
emoteTab[2].innerHTML += '<span style="cursor:pointer;" id="'
+ EmoteNameLines[i]
+ '" data-usage="' + EmoteUsageLines[i] + '">'
+ '<img src="' + EmoteURLLines[i] + '" /></span>'
;
} else {
alert ("The maximum emote (" + EmoteNameLines[i] + ") size is (36x36)");
}
}
//-- Only add events when innerHTML overwrites are done.
var targetSpans = emoteTab[2].querySelectorAll ("span[data-usage]");
for (var J in targetSpans) {
targetSpans[J].addEventListener ("click", appendEmote, false);
}
Where appendEmote is like:
function appendEmote (zEvent) {
//-- this and the parameter are special in event handlers. see the linked doc.
var emoteUsage = this.getAttribute ("data-usage");
shoutdata.value += emoteUsage;
}
WARNINGS:
Your code reuses the same id for several elements. Don't do this, it's invalid. A given ID should occur only once per page.
Every time you use .outerHTML or .innerHTML, you trash any event handlers on the affected nodes. If you use this method beware of that fact.
Make sure you are using Javascript module or not?!
if using js6 modules your html events attributes won't work.
in that case you must bring your function from global scope to module scope. Just add this to your javascript file:
window.functionName= functionName;
example:
<h1 onClick="functionName">some thing</h1>
I think you put the function in the $(document).ready.......
The functions are always provided out the $(document).ready.......
I got this resolved in angular with (click) = "someFuncionName()" in the .html file for the specific component.
Check the casing of your functions.
onclick="sillyLongFunctionName"
and
function sillylongFunctionName() { ...
Are not identical. Hard to spot sometimes!
If the function is not defined when using that function in html, such as onclick = ‘function () ', it means function is in a callback, in my case is 'DOMContentLoaded'.
See that your function is not in a callback function if you are using an external js file.
Removing the callback function would do the trick
(function() { //comment this out
//your code
})(); //comment this out

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