innerHTML = HTML & JQuery, JQuery doesn't execute - javascript

I am using jscript to insert HTML.
function pluginOrderTotals(OrderTotals) {
var orderTotalsHTML = "";
if (OrderTotals != "") {
orderTotalsHTML = "<a id='OrderTotals' href=''>Order Totals</a><p id='OrderTotalText'>" + OrderTotals + "</p><script>$('#OrderTotals').click(function () { $('#OrderTotalText').toggle('fast');});";
}
document.getElementById("pluginWidgets2Div").innerHTML = orderTotalsHTML;}
The HTML part of the variable is passed just fine, but the JQuery animations do not work. If I hard code this in the HTML like below the animations work fine.
<div id="pluginWidgets2Div">
<a id="OrderTotals" href="">Order Totals</a>
<p id="OrderTotalText">Hiya<br />
Such interesting text, eh?</p>
<a id="FreightView" href="">View Freight</a>
<p id="FreightViewText" style="display: none">Hiya<br />
Such interesting text, eh?</p>
Another (3)
Menu item 4
One more (5)
<script>
$("#OrderTotals").click(function () {
$("#OrderTotalText").toggle("fast");
});
$("#FreightView").click(function () {
$("#FreightViewText").toggle("fast");
});
</script></div>
Thanks for your help.

.innerHTML doesn't execute script elements. You can use .html() in jQuery ...
Or do the sensible thing which is just running that code directly:
function pluginOrderTotals(OrderTotals) {
var orderTotalsHTML = "";
if (OrderTotals != "") {
orderTotalsHTML = "<a id='OrderTotals' href=''>Order Totals</a><p id='OrderTotalText'>" + OrderTotals + "</p>";
}
document.getElementById("pluginWidgets2Div").innerHTML = orderTotalsHTML;
$('#OrderTotals').click(function () {
$('#OrderTotalText').toggle('fast');
});
}

There's a nice unobtrusive way to have this code waiting in the wings so that it will work. When inserting the HTML, skip the JavaScript - handle it separately.
function pluginOrderTotals(OrderTotals) {
var orderTotalsHTML = "";
if (OrderTotals != "") {
orderTotalsHTML = "<a id='OrderTotals' href=''>Order Totals</a><p id='OrderTotalText'>" + OrderTotals + "</p>";
}
document.getElementById("pluginWidgets2Div").innerHTML = orderTotalsHTML;
}
$(document).ready(function(){
$("#pluginWidgets2Div").on("click", "#OrderTotals", function () {
$("#OrderTotalText").toggle("fast");
});
});
The jQuery will apply to the HTML if/when it's inserted, and your HTML doesn't need to have any JavaScript in it.

You haven't closed the <script> tag:
orderTotalsHTML = "<a id='OrderTotals' href='#'>Order Totals</a><p id='OrderTotalText'>" + OrderTotals + "</p><script>$('#OrderTotals').click(function () { $('#OrderTotalText').toggle('fast');});</script>";

Related

This code brakes my divs. Is it becasue of the global variable?

(function() {
if ( !window.BG || typeof window.BG !== 'object') {
window.BG = {};
}
var BG = window.BG;
BG.votdWriteCallback = function(json) {
var votd = json.votd;
document.write('<div>' + votd.text);
document.write(' </br><a target="_blank" href="' + votd.permalink +'">' + votd.display_ref + '</a>');
if (votd.audiolink) {
document.write(' <img alt="Listen to chapter" src="//www.biblegateway.com/assets/images/audio/sound.gif" border=0/>');
}
document.write('</div>');
};
window.BG = BG;
})();
Want to clean this script because for some reason it's breaking my HTML divs but I can't see where the problem is.
sorry, just saw now that im writing a extra div in the
document.write('</div>');
I know its bad practice to use document.write.
This is some old code that im trying to clean up

See if there is a form inside a div

I have a div with an id like: comment-box-5 and I want to see using javascript if there is a form inside of it if so remove it if not add it (so it toggles when I call the function). I wrote this piece of code to try to do this:
function reply(id){
console.log(document.getElementById('comment-id-' + id).innerHTML.indexOf(document.getElementById('form-' + id)));
if (document.getElementById('comment-id-' + id).innerHTML.indexOf(document.getElementById('form-' + id))) {
var form = replyFn(id);
document.getElementById('comment-id-' + id).appendChild(form);
} else {
//for toogle effect
document.getElementById('comment-id-' + id).removeChild(document.getElementById("form-" + id));
}
}
And I tried executing it but console.log(document.getElementById('comment-id-' + id).innerHTML.indexOf(document.getElementById('form-' + id))); prints -1 even if there is a form inside.
What am I doing wrong? how can I actually see if there is a form in the div?
You could change your condition to :
if ( document.querySelector('#comment-id-' + id +'>#form-' + id) ) {
//Your if logic
}else{
//Your else logic
}
Snippet :
var id = 1;
if (document.querySelector('#comment-id-' + id + '>#form-' + id)) {
console.log('Remove form');
} else {
console.log('Add form');
}
<div id="comment-id-1">
<form id="form-1"></form>
</div>
Try using contains on the div without innerHTML like below, I changed the code from yours a bit to do the example but it should work for yours as well.
console.log(document.getElementById('comment-id-1').contains(document.getElementById('form-id-1')));
<div id="comment-id-1"><form id="form-id-1"></form></div>

Javascript function isn't recognized

I don't have many knowlege in javascript so I don't know what is the problem here,
I create divs dynamically in js and each div call a function when is clicked but the function is not recongized. This is part of the code
for (......) {
var listatema = document.createElement("div");
listatema.innerHTML += "<a href='javascript: void(0)' onClick='functest(" + pag + ")'>" + temat + "</a>";
document.getElementById('menu').appendChild(listatema);}
}
"tema" is a text, the function "functest" has an argument "pag[aux]", this is a number.
The function is:
function functest(arg){
console.log(arg)
}
other alternative that i tried is change that: onClick='"+ functest(pag) +"':
i change the position of Quotation marks "" and the function work good but it is executed when the page is loaded, it don't wait to do click.
Your code should work if you're doing something like:
function functest(arg) {
console.log(arg);
}
for (var i = 0; i < 10; i++) {
var listatema = document.createElement("div");
listatema.innerHTML += "<a href='javascript: void(0)' onClick='functest(" + i + ")'>" + i + "</a>";
document.getElementById('menu').appendChild(listatema);
}
<div id="menu"></div>
I would, however, recommend using addEventListener or setting the onClick handler on the document element object rather than setting the innerHTML. Note that setting innerHTML is not advised, especially when rendering user input. See https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#Security_considerations. In your case, it probably isn't really an issue, but it's good practice to avoid it if you can :)
for (var i = 0; i < 5; i++) {
var wrapper = document.createElement("div");
var listatema = document.createElement("a");
listatema.textContent = i;
listatema.href = "javascript:void(0)";
listatema.addEventListener('click', function(e) {
console.log(this.i);
}.bind({ i : i }));
wrapper.appendChild(listatema);
document.getElementById('menu').appendChild(wrapper);
}
<div id="menu"></div>
onClick='functest(\""+ pag +"\")'
you forgot to quote the parameter.

li append function not work

I'm using blogger as my blogging platform. In my blog homepage, I create a function to grab all images from single post for each post (there are 5 posts in my homepage), then append all images from single post to single slider, for each post.
This is my function script (I place it after <body> tag):
<script type='text/javascript'>
//<![CDATA[
function stripTags(s, n) {
return s.replace(/<.*?>/ig, "")
.split(/\s+/)
.slice(0, n - 1)
.join(" ")
}
function rm(a) {
var p = document.getElementById(a);
img = p.getElementsByTagName("img").each( function(){
$(".flexslider .slides").append($("<li>").append(this));
});
p.innerHTML = '<div class="entry-container"><div class="entry-content"><div class="entry-image"><div class='flexslider'><ul class='slides'></ul></div></div><div class="entry-header"><h1>' + x + '</h1></div><p>' + stripTags(p.innerHTML, SNIPPET_COUNT) + '</p></div></div>'
}
//]]>
</script>
Then my variable, each post have single variable, different for each post based on it's ID:
<script type='text/javascript'>var x="Post Title",y="http://myblog.url/post-url.html";rm("p8304387062855771110")
My single post markup:
<span id='p8304387062855771110'></span>
The problem is, the append function in my script not work. Am I forget something in my code?
Your jQuery/JavaScript is very ropey. There is no method each on a nodelist. Try not to mix jQuery/JavaScript up so much. And you might consider using a array/join on the html you want to insert to keep the line length readable. That way you might have noticed that your HTML quotes were not consistent.1
var $p = $('#' + a);
$p.find('img').each(function () {
var html = $('<li>').append($(this))
$('.flexslider .slides').append(html);
});
var html = [
'<div class="entry-container"><div class="entry-content">',
'<div class="entry-image"><div class="flexslider">',
'<ul class="slides"></ul></div></div><div class="entry-header">',
'<h1><a href="',
y,
'">',
x,
'</a></h1></div><p>',
stripTags(p.innerHTML, SNIPPET_COUNT),
'</p></div></div>'
].join('');
$p.html(html);
1 Personally I prefer single quotes for JS work and double quotes for HTML attributes and never the twain shall meet.
I think <li> doesnt work try li like this:
$(".flexslider .slides").append($("li").append(this));
You could get rid of type="text/javascript" and //<![CDATA[, it is 2014, after all ;-)
Also, .*? is not what you mean.
<script>
function stripTags(s, n) {
return s.replace(/<[^>]*>/g, "") // Be careful with .*? : it is not correct
.split(/\s+/)
.slice(0, n - 1)
.join(" ")
}
function rm(id) {
var $p = $('#' + id);
img = $p.find("img").each( function(){
$(".flexslider .slides").append($("<li>").append(this));
});
p.innerHTML = '<div class="entry-container"><div class="entry-content"><div class="entry-image"><div class="flexslider"><ul class="slides"></ul></div></div><div class="entry-header"><h1>' + x + '</h1></div><p>' + stripTags(p.innerHTML, SNIPPET_COUNT) + '</p></div></div>'
}
</script>

How to get the value of id of innerHTML?

I have created a html like this:
<body onload = callAlert();loaded()>
<ul id="thelist">
<div id = "lst"></div>
</ul>
</div>
</body>
The callAlert() is here:
function callAlert()
{
listRows = prompt("how many list row you want??");
var listText = "List Number";
for(var i = 0;i < listRows; i++)
{
if(i%2==0)
{
listText = listText +i+'<p style="background-color:#EEEEEE" id = "listNum' + i + '" onclick = itemclicked(id)>';
}
else
{
listText = listText + i+ '<p id = "listNum' + i + '" onclick = itemclicked(id)>';
}
listText = listText + i;
//document.getElementById("lst").innerHTML = listText+i+'5';
}
document.getElementById("lst").innerHTML = listText+i;
}
Inside callAlert(), I have created id runtime inside the <p> tag and at last of for loop, I have set the paragraph like this. document.getElementById("lst").innerHTML = listText+i;
Now I am confuse when listItem is clicked then how to access the value of the selected item.
I am using this:
function itemclicked(id)
{
alert("clicked at :"+id);
var pElement = document.getElementById(id).value;
alert("value of this is: "+pElement);
}
But getting value as undefined.
Any help would be grateful.
try onclick = itemclicked(this.id) instead of onclick = 'itemclicked(id)'
Dude, you should really work on you CodingStyle. Also, write simple, clean code.
First, the html-code should simply look like this:
<body onload="callAlert();loaded();">
<ul id="thelist"></ul>
</body>
No div or anything like this. ul and ol shall be used in combination with li only.
Also, you should always close the html-tags in the right order. Otherwise, like in your examle, you have different nubers of opening and closing-tags. (the closing div in the 5th line of your html-example doesn't refer to a opening div-tag)...
And here comes the fixed code:
<script type="text/javascript">
function callAlert() {
var rows = prompt('Please type in the number of required rows');
var listCode = '';
for (var i = 0; i < rows; i++) {
var listID = 'list_' + i.toString();
if (i % 2 === 0) {
listCode += '<li style="background-color:#EEEEEE" id="' + listID + '" onclick="itemClicked(this.id);">listItem# ' + i + '</li>';
}
else {
listCode += '<li id="' + listID + '" onclick="itemClicked(this.id);">listItem# ' + i + '</li>';
}
}
document.getElementById('thelist').innerHTML = listCode;
}
function itemClicked(id) {
var pElement = document.getElementById(id).innerHTML;
alert("Clicked: " + id + '\nValue: ' + pElement);
}
</script>
You can watch a working sample in this fiddle.
The problems were:
You have to commit the id of the clicked item using this.id like #Varada already mentioned.
Before that, you have to build a working id, parsing numbers to strings using .toString()
You really did write kind of messy code. What was supposed to result wasn't a list, it was various div-containers wrapped inside a ul-tag. Oh my.
BTW: Never ever check if sth. is 0 using the ==-operator. Better always use the ===-operator. Read about the problem here
BTW++: I don't know what value you wanted to read in your itemClicked()-function. I didn't test if it would read the innerHTML but generally, you can only read information from where information was written to before. In this sample, value should be empty i guess..
Hope i didn't forget about anything. The Code works right now as you can see. If you've got any further questions, just ask.
Cheers!
You can pass only the var i and search the id after like this:
Your p constructor dymanic with passing only i
<p id = "listNum' + i + '" onclick = itemclicked(' + i + ')>
function
function itemclicked(id)
{
id='listNum'+i;
alert("clicked at :"+id);
var pElement = document.getElementById(id).value;
alert("value of this is: "+pElement);
}
is what you want?
I am not sure but shouldn't the onclick function be wrapped with double quotes like so:
You have this
onclick = itemclicked(id)>'
And it should be this
onclick = "itemclicked(id)">'
You have to modify your itemclicked function to retrieve the "value" of your p element.
function itemclicked( id ) {
alert( "clicked at :" + id );
var el = document.getElementById( id );
// depending on the browser one of these will work
var pElement = el.contentText || el.innerText;
alert( "value of this is: " + pElement );
}
demo here

Categories

Resources