Calling a method while setting innerHTML of an element - javascript

I am struggling with calling a method while setting innerHTML.
I apologize if there is a straightforward answer I have overlooked, but at the moment I am stuck.
Se the code below:
"<a href='#' onclick='removeEntry('" + element.id + "')'><span class='fa fa-times'></span></a>"
You can see that there's a mess regarding the quotes.
Is there a third way to type quotes or something of the kind that can allow me to call "removeEntry(element.id)"? I need quotes around element.id in order to call removeEntry. Any suggestions on how to solve this in a different way?

You should replace
"<a href='#' onclick='removeEntry('" + element.id + "')'><span class='fa fa-times'></span></a>"
with
"<a href='#' onclick='removeEntry(\"" + element.id + "\")'><span class='fa fa-times'></span></a>"
In fact, the problem is with you current code, the a tag onclick property will be looking like onclick='removeEntry('myId')'
Note there's imbricated simple quotes, breaking your function call. Replace the id simple quotes by escaped double quotes , and it'll give you onclick='removeEntry("myId")' that is fine :)
Edit : Anyway, if you're targeting recent browser, you could try ES6 template literals, that will give you the following line :
var html = `<span class="fa fa-times"></span>`;
This helps to avoid struggling with your quotes. Note that the variable inclusion in the template literal looks like PHP do.

This:
"<a href='#' onclick='removeEntry('" + element.id + "')'><span class='fa fa-times'></span></a>"
will create an element like this:
<a href='#' onclick='removeEntry('someId')'><span class='fa fa-times'></span></a>
Which is not correct. What you need to do is to either:
Use the other quotes " (but you have to escape them):
like this:
"<a href='#' onclick='removeEntry(\"" + element.id + "\")'><span class='fa fa-times'></span></a>"
to create an element like this:
<a href='#' onclick='removeEntry("someId")'><span class='fa fa-times'></span></a>
Or Add a backslash \ to the ' quotes (you have to escape the backslashes as well):
like this:
"<a href='#' onclick='removeEntry(\\'" + element.id + "\\')'><span class='fa fa-times'></span></a>"
to create an element like this:
<a href='#' onclick='removeEntry(\'someId\')'><span class='fa fa-times'></span></a>

'<a href="#" onclick="removeEntry(' + element.id + ')">
<span class="fa fa-times"></span>
</a>'
This should work out. You can encode double quotes in single quotes and you want this whole expression as a string.so a string with variable can be written as
string1 = string2 + variable +string3;
Or for a multi lines string in JavaScript you can use back ticks.
`<a href="#" onclick="removeEntry(' + element.id + ')">
<span class="fa fa-times"></span>
</a>`

Related

<i class="fa fa-trash"> is not working in <span></span>

I was going through the solutions of Uncaught SyntaxError: missing ) after argument list, and tried every other way to sort it out but I am still getting this error with this code
$("input").on("keypress",function(event){
if(event.which === 13)
{
var ToDotext=($(this).val());
$("ul").append("<li><span><i class="fa fa-trash"></span> " + ToDotext + "</li>");
$(this).val("");
}
}
);
whenever I put <i class="fa fa-trash" in <span></span> I am getting this error, without <i class="fa fa-trash"> things are working fine.
Change the appending line to this.
$("ul").append("<li><span><i class='fa fa-trash'></i></span> " + ToDotext + "</li>");
Changes:
fa fa-trash is in single quotes as you are using double quotes outside.
close the i tag
Suggestions:
Instead of using <i> inside <span>, apply the class on span or remove span altogether and keep i tag.
Use jQuery element creation methods. like this.
$('ul li ').html($('<i>', {class: 'fa fa-trash'}));
Use this code
$("input").on("keypress",function(event){
if(event.which === 13)
{
var ToDotext=($(this).val());
$("ul").append("<li><span><i class='fa fa-trash'></i></span>"+ ToDotext + "</li>");
$(this).val("");
}
});
I found the error in your script.
$("ul").append("<li><span><i class="fa fa-trash"></span>"+ToDotext+"</li>");
If you add component, with this code, the actual components are added as follows.
<li><span><i class=fa fa-trash></span>ToDoText</li>
As you see above, the class names of the <i> tag must be quoted with " or ' but it is not like that.
It is because you used the same quotes adding the components.
If you change "fa fa-trash" -> 'fa fa-trash', the problem will be solved.
You can't have double quotations inside double quotations, simple example:
open your console:
var newElem = "<h1 class="rock">Hello There !!</h1>";
newElem // Uncaught SyntaxError: Unexpected identifier
You will have to enclose you class and other html attributes inside a single quotations, like so:
var newElem = "<h1 class='rock'>Hello There !!</h1>";
The below line:
$("ul").append("<li><span><i class='fa fa-trash'></span> " + ToDotext + "</li>");
Would have to change to:
$("ul").append("<li><span><i class="fa fa-trash"></span> " + ToDotext + "</li>");
Additional ::- if you writing long concatenations you probably want to SPLIT IT UP INTO ADDITIONAL LINK

Escaping quotes coming from JSON

I get some data from JSON and put it as a custom attribut data-info into an a-tag. When clicking on this link, the information should appear:
$("#div").append("<a href='#' data-info='" + value.info + "'>" + value.name "</a>");
Unfortunately, JSON may contain some quotes that break my code:
Some text
How can I escape all quotes coming from JSON?
Do it properly.
var a = document.createElement('a');
a.setAttribute("href","#");
a.setAttribute("data-info",value.info);
a.appendChild(document.createTextNode(value.name));
$("#div").append(a);
Done ;)
With jQuery you can use attr
var $link = $('<a href="#" />').text(value.name).attr('data-info', value.info);
$("#div").append($link);
Here is what you wanted:
$("#div").append("<a href='#' data-info='" + value.info.replace("'", "\'") + "'>" + value.name "</a>");
But you should do it like #Niet the Dark Absol's answer 😉

Links not working in IE and Firefox with jquery generated markup

I'm writing a javascript app that dynamically generates buttons that lead users to links about different products.
They look like this:
The problem is when they're generated the links contained within them work in chrome but not in IE or Firefox.
Here's the HTML:
HTML
<div class="row">
<div class="button-class">
</div>
</div>
This is the code I use to generate them:
JQUERY
buttons: function(num) {
$(".button-class").html("<div class='text-center'><ul class='list-inline'><li><button class='btn btn-success'><a href=" + state.greens[num].website + " target='_blank'>Company Website</a></button></li> <li><button class='btn btn-success' data-toggle='modal' data-target='#myModal'>View the Label</button></li></ul></div>");
if (state.greens[num].link !== false) {
$(".button-class ul").append("<li><button class='btn btn-success'><a href=" + state.greens[num].link + " rel='nofollow' target='_blank'>Get It On Amazon</a></button></li>");
}
if (state.greens[num].review !== false) {
$(".button-class ul").append("<li><button class='btn btn-success'><a href=" + state.greens[num].review + " target='_blank'>Read The Review</a></button></li>");
}
},
buttons is part of an object called display and is called by display.buttons();
The two if statements check to see if certain types of links exist within a product's object and then appends them to the UL if the ydo.
The buttons generate correctly but they don't open up the links when clicked in Firefox and IE (maybe Safari but I haven't checked).
What's more confusing to me is that the html being generated looks semantically correct.
For example this is the html shown in the Firefox debugger that's not working:
Doesn't make sense to me.
If you want to go to a live version of the page you can see it here: superfood picker
Then go to the last section that reads "Click On A Product's Detail Page To Learn More" and looks like this:
Click on one of the products and it'll take you to the buttons that I'm talking about.
It's not semantically correct because you need to wrap in quotes the href
buttons: function(num) {
$(".button-class").html("<div class='text-center'><ul class='list-inline'><li><button class='btn btn-success'><a href='" + state.greens[num].website + "' target='_blank'>Company Website</a></button></li> <li><button class='btn btn-success' data-toggle='modal' data-target='#myModal'>View the Label</button></li></ul></div>");
if (state.greens[num].link !== false) {
$(".button-class ul").append("<li><button class='btn btn-success'><a href='" + state.greens[num].link + "' rel='nofollow' target='_blank'>Get It On Amazon</a></button></li>");
}
if (state.greens[num].review !== false) {
$(".button-class ul").append("<li><button class='btn btn-success'><a href='" + state.greens[num].review + "' target='_blank'>Read The Review</a></button></li>");
}
},
Note that's it's best if you change double quotes instead single quotes and viceversa.

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

AJAX innerHTML. Change links. Possibly a " or ' problem

What I want is a hyperlink More when clicked on runs some javascript function and also changes to a hyperlink Less. Heres what I have which doesnt work. It runs the ajaxpage function fine but not moreToLess. I think its my use of " and ' in the javascript.
<script type="text/javascript">
function moreToLess(){
document.getElementById('tagLinks').innerHTML = '<a href=# OnClick="ajaxpage('/TagCloud?id=EDI_0009&count=20', 'tagcloud');lessToMore()" >Less</a>';
}
function lessToMore(){
document.getElementById('tagLinks').innerHTML = '<a href=# OnClick="ajaxpage('/TagCloud?id=EDI_0009&count=50', 'tagcloud');moreToLess()" >More</a>';
}
</script>
<span id=tagLinks ><a href=# OnClick="ajaxpage('/TagCloud?id=EDI_0009&count=50', 'tagcloud');moreToLess()" >More</a></span>
Yes it is, just escape your single quotes inside of the double quotes that you have in your javascript.. ala \'
<script type="text/javascript">
function moreToLess(){
document.getElementById('tagLinks').innerHTML = '<a href=# OnClick="ajaxpage(\'/TagCloud?id=EDI_0009&count=20\', \'tagcloud\');lessToMore()" >Less</a>';
}
function lessToMore(){
document.getElementById('tagLinks').innerHTML = '<a href=# OnClick="ajaxpage(\'/TagCloud?id=EDI_0009&count=50\', \'tagcloud\');moreToLess()" >More</a>';
}
</script>
<span id=tagLinks ><a href=# OnClick="ajaxpage('/TagCloud?id=EDI_0009&count=50', 'tagcloud');moreToLess()" >More</a></span>
You have to escape the ' characters inside the quote:
'<a href=# OnClick="ajaxpage(\'/TagCloud?id=EDI_0009&count=20\', \'tagcloud\');lessToMore()" >Less</a>'
I'm not sure if there's anything else wrong, but I think you need to escape your single-quotes that are within other single-quotes:
document.getElementById('tagLinks').innerHTML = '<a href=# OnClick="ajaxpage(\'/TagCloud?id=EDI_0009&count=20\', \'tagcloud\');lessToMore()" >Less</a>\';
It is indeed a quote issue, you can escape the ' character with a \ character
<script type="text/javascript">
function moreToLess(){
document.getElementById('tagLinks').innerHTML = '<a href=# OnClick="ajaxpage(\'/TagCloud?id=EDI_0009&count=20\', \'tagcloud\');lessToMore()" >Less</a>';
}
function lessToMore(){
document.getElementById('tagLinks').innerHTML = '<a href=# OnClick="ajaxpage(\'/TagCloud?id=EDI_0009&count=50\', \'tagcloud\');moreToLess()" >More</a>';
}
</script>
<span id=tagLinks ><a href=# OnClick="ajaxpage('/TagCloud?id=EDI_0009&count=50', 'tagcloud');moreToLess()
This kind of confusion is why innerHTML is not always a win. You've got JavaScript embedded in HTML embedded in a JavaScript string literal embedded in more HTML, it's no wonder you're confused.
Here's a simpler version based on toggling the link through DOM methods.
<a id="tagLinks" href="/TagCloud?id=EDI_0009&count=50">more...</a>
<script type="text/javascript">
var ismore= false;
document.getElementById('tagLinks').onclick= function() {
ajaxpage(this.href);
ismore= !ismore;
this.href= '/TagCloud?id=EDI_0009&count='+(ismore? 20 : 50);
this.firstChild.data= ismore? 'less...' : 'more...';
return false;
};
</script>

Categories