How to pass JavaScript arguments using inner HTML - javascript

I am new to JavaScript and I am currently stuck on an issue. Basically, I using an API to search for anime, get the html image, synopsis, and name and put them in a table. That works fine. What I am trying to do is add an onlick for each name in the table to perform a function using the name of the anime as an argument. I have tried using "\'", the escape character, and it didn't work. Here is my code for each row:
nameAndSynopsis.innerHTML = "<table style='border: 1px solid black'><tr><td style='color:blue' onclick='getEpisodes(\'" + anime_name + "\')'>" + anime_name + "</td></tr><br><br><br><tr><td>" + anime_synopsis + "</td></tr></table>";`
When I run my code, the console says Unexpected end of input and here are the results from the source tab when I use inspect on my web page
`getEpisodes(`
Any help would be greatly appreciated.

If you have to use quotes, here how you will do it:
var functionname = "getEpisodes('" + anime_name + "')";
nameAndSynopsis.innerHTML = '<table style="border: 1px solid black"><tr><td style="color:blue" onclick="' +functionname+ '">' + anime_name + '</td></tr><br><br><br><tr><td>' + anime_synopsis + '</td></tr></table>';
I have added functionname in separate line to simply it. It can be done in single line as well.
<div id="nameAndSynopsis"></div>
<script>
function getEpisodes(something) {
console.log("ok.........");
}
var nameAndSynopsis = document.getElementById("nameAndSynopsis");
var anime_name = "anime_name";
var anime_synopsis = "anime_synopsis";
var functionname = "getEpisodes('" + anime_name + "')";
nameAndSynopsis.innerHTML = '<table style="border: 1px solid black"><tr><td style="color:blue" onclick="' + functionname + '">' + anime_name + '</td></tr><br><br><br><tr><td>' + anime_synopsis + '</td></tr></table>';
</script>

Try using template literals instead of all the quotes like this.
nameAndSynopsis.innerHTML = `<table style='border: 1px solid black'><tr><td style='color:blue' onclick=getEpisodes(${anime_name})> ${anime_name} </td></tr><br><br><br><tr><td>${anime_synopsis}</td></tr></table>`

You are using single-quote around the attribute value onclick=' <-- '
Then you are escaping the single quote, so it comes out like this ..
onclick='getEpisodes('yourAnimeName')'
Which sets your onclick attribute to getEpisodes(
This may not make sense and you may be asking, how does it end up like that, didn't i just ESCAPE those quotes?
Well, yes and no, you escaped them in the current javascript context. But since that is then inserted into the DOM as html, the html parser won't see those single-quotes as being escaped.
Try using double-quotes instead.
onclick='getEpisodes(\""+anime_name+"\")'
or
onclick=\"getEpisodes('"+anime_name+"')\"

Your code is ending with an unkown string there, right at the end
</table>";` <---- remove this last string
It should be ending like this
</table>";

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;

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!

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

jQuery "undefined" prints when appending to html element

I'm making a jQuery MP3 player. The song structure is first generated (including the information about the song), and then the structure is appended to a div using jQuery like this:
function loadFromPlaylist(playlist) {
var songsStructure;
for (var i=0; i<playlist.length; i++) {
songsStructure +=
"<div id='song" + i + "'>" +
"<span class='mpPlaylistArtist'>" + playlist[i].artist + "</span>" +
"<span class='mpPlaylistSong'>" + playlist[i].song + "</span>" +
"<span class='mpPlaylistAlbum'>" + playlist[i].album + "</span>" +
"</div>";
}
$('#mpTracks').append(songsStructure);
}
This works perfectly except for one thing. When the items are displayed in the browser, a string ("undefined") is printed above the songs, like so:
<div id="mpTracks">
"undefined"
<div id="song0">...</div>
<div id="song1">...</div>
</div>
Googling this problem yielded alot of related problems but that didn't help me.
Does anyone know what the problem might be?
Initialize your variable to an empty string, before using it:
var songsStructure = '';
You did not set an initial value, so it is set to undefined. According to JS rules for concatination, this undefinedis then concatenated with the strings generated by the for loop leading to your result.
You have to initialize the songsStructure variable.
Write
function loadFromPlaylist(playlist) {
var songsStructure="";
and your problem will be solved.

Categories