Deleting and inserting Code in a DIV via jQuery - javascript

I know this has been adressed before, but I can't seem to get it working for me.
I am trying to create a football pitch with editable players via HTML/JavaScript/jQuery.
I can produce the field the first time when loading the page without any problems. The code looks like this:
<div id="pitch" class="updateAble">
<script type="text/javascript">
appBuilder(team1, team2);
</script></div>
appBuilder() looks like this:
var appBuilder = function (team1, team2) {
team1.Display();
team2.Display(); }
It simply creates the players on the pitch for both teams. As it does. I now want to push an input-button to call a function appUpdate(), which deletes the content of #pitch and puts the appBuilder()-part in again as to renew it (if I changed or added players):
var appUpdate = function () {
var newContent = "<script type='text/javascript'>appBuilder(team1, team2);</script>";
var updateItem = $('#pitch');
updateItem.empty();
updateItem.append(newContent);}
Here is what drives me nuts: It seems to work just fine up to and including the empty()-function. So the code has to be fine.
But when I try to append newContent to the #pitch-DIV, the programm seems to completely delete everything inside <head> and <body> it recreates a clean html-file (with empty html-, head-, body-tags) and inserts my players inside <body>.
Any ideas as to why it is doing that?
Thanks in advance!
UPADTE: The solution was a rookie mistake (which is fitting, since I'm a rookie). The Team.Display()-method was trying to do a document.write() call. As I learned: If you call document.write once the document is fully loaded, it will delete your site. Thanks to jfriend for the solution! :)

If you call document.write() AFTER the document has finished loading, then it will clear the current document and create a new empty one.
What you need to do is use DOM insertion operations rather than document.write() to add/change content in the DOM once the document has already loaded.
My guess is that the .Display() method is using document.write() and you need to change the way it works to insert content into a parent node rather than write it into the current position.
Some ways to insert content:
var newNode = document.createElement("div");
node.appendChild(newNode);
node.innerHTML = "<div>My Content</div>";
Or, if you're using jQuery, you can use it's wrappers for this:
obj.append("<div>My Content</div>");
obj.html("<div>My Content</div>");

.html() would empty and fill the div at once. Have you tried that ?
updateItem.html(newContent);

I proposed a JQuery replacement for your code that does what you want, ion the style of your own typing.
Note that I kept the .html() call to mimic your "empty()" function, but it is not necessary. Simply put he code in the append, straight into the html() et get rid of the extra unnecessary remaing bit of code.
My code replacement, as a 100% functioning .html file. Hope it helps, cheers.
<html>
<header>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
var appBuilder = function (team1, team2) {
//team1.Display();
//team2.Display();
}
var team1, team2;
</script>
</header>
<body>
<div id="pitch" class="updateAble">
<script type="text/javascript">
appBuilder(team1, team2); // Original code to be updated
</script>
</div>
<script>
var appUpdate = function () {
$("#pitch").html("<!-- Old javscript code has been flushed -->").append($("<script />", {
html: "appBuilder(team1, team2); // brand new, replaced code"
}));
}
appUpdate();
</script>
</body>
</html>

Related

javascript set variable from .text method

I'm new in javascript development and I want to ask how to set variable from text method.
Example: in this code have a text method
$('.phone').text(theRestaurant.phone);
$('.location').text(theRestaurant.location);
$('.info').text(theRestaurant.info);
in the Html file, when I create any class from these will print the value from JSON file.
Example :
<div class='phone'></div>
Output: (000)000-9999
source code:
<div class='phone'>(000)000-9999</div>
I try to set this in variable but it doesn't work.
My try:
var phone = theRestaurant.phone
I want to set it in variable because I need to put it inside href value like so:
<script>
var phone = 'tel:' + phone
document.getElementById("phone").href = phone;
</script>
I hope everything clear. and If have an other solution please tell about it.
Thanks
Have you wrapped your jQuery code in a document.ready() wrapper?
If not, then the javascript might run before the page has had time to create the elements in the DOM, and nothing will work.
<script>
$(document).ready(function(){
//all javascript/jQuery code goes in here
});
</script>
Also, see my comment above about mixing up "ByClassName" and "ByID"
Answer came from #itsgoingdown
this code in main javascript file:
var phone=document.getElementById('phone').innerHTML; document.getElementsByClassName("phone")[0].href = phone;

remove element <script> in body

I got a script converter like this
var currency_data='USD,0.712497,0.01|AUD,0.5576,0.05|AED,0.194009,0.25|BRL,0.248647,0.01|JPY,0.00594888,1|GBP,1.09482,0.01|CAD,0.572195,0.01|CNY,0.115772,0.5|EUR,0.795717,0.01|INR,0.0115219,0.1|ILS,0.178705,0.01|QAR,0.195741,1|RUB,0.0114246,0.01|SAR,0.189999,1|SGD,0.522129,0.01|THB,0.0220219,0.25';
var currency_sdrPer=new Array(),currency_Unit=new Array();currency_make_arrays();function currency_make_arrays(){var d=currency_data.split("|");for(var e=0;e<d.length;e++){var b=d[e].split(","),f=b[0];currency_sdrPer[f]=b[1];currency_Unit[f]=b[2]}};
function currency_rnd(h,e){h=Math.round(h/e)*e+".";var g=(e+".").split("."),c=h.split("."),b=c[1],a=g[1].length,d=b.length;if(d>a){b=b.substring(0,a)}for(var f=0;f<a-d;f++){b+="0"}return c[0]+(a==0?"":"."+b)}function currency_convert(f,d,c){var e=currency_sdrPer;if(!e[d]||!e[c]){return""}return currency_format(f*(e[d]/e[c]),currency_Unit[c])}function currency_format(c,f){var g=typeof currency_thousandsSeparator=="string"?currency_thousandsSeparator:",",b=typeof currency_decimalSeparator=="string"?currency_decimalSeparator:".",f=(typeof currency_decimalDigits=="number")?(1/Math.pow(10,currency_decimalDigits)):(typeof f=="number"?f:0.01),j=typeof currency_thousandsSeparatorMin=="number"?currency_thousandsSeparatorMin:3;if(typeof currency_round=="boolean"&&currency_round){c=currency_rnd(c,f)}var i=(""+c).split("."),h=i[0],e=i.length>1?b+i[1]:"",a=/(\d+)(\d{3})/;if(g!=""){while(a.test(h)&&h.length>j){h=h.replace(a,"$1"+g+"$2")}}return h+e};
function conversion(e,d,c){document.write(currency_convert(e,d,c))}function currency_getRateHTML(d,c){var g=currency_convert(1,d,c);if(g==""){return""}var f=d+"_"+c+".html";if(c<d){f=c+"_"+d+".html"}f="http://coinmill.com/"+f;var e=unescape("%3Ca+href%3D%22%24link%22%3E%24from_the_name+is+worth+%3Cb%3E%24rate%3C/b%3E+%24to_plural_name%3C/a%3E%3Cbr%3E");if(typeof currency_template!="undefined"){e=currency_template}return e.replace("$link",f).replace("$rate",g).replace("$from_abbrev",d).replace("$from_name",d).replace("$from_plural_name",d+"s").replace("$from_the_name","the "+d).replace("$to_abbrev",c).replace("$to_name",c).replace("$to_plural_name",c+"s").replace("$to_the_name","the "+c)}function currency_showRate(d,c){document.write(currency_getRateHTML(d,c))}function currency_showRates(){for(var e=0;e<currency_rate_list.length;e++){var d=currency_rate_list[e];e++;if(e<currency_rate_list.length){var c=currency_rate_list[e];currency_showRate(d,c)}}}if(typeof currency_rate_list!="undefined"){currency_showRates()};
after element <head>
<script>
var currency_round=true;
</script>
and the calling inside after <body>:
<div>USD 60.61 = GBP <script>conversion(60.61,"USD","GBP");</script></div>
however, I really mind that there are <script> and </script> element inside body where as it's not good for html validation.
Is there any way to change it to be or element?
If you really want to move it out of the body (and there doesn't seem to be any point in doing so, it isn't invalid to have a script there) then you will need to:
Create an element in the body to put the content in
Replace all the document.write statements with DOM methods
Call the conversion function after the element becomes available (e.g. with an load event handler)
I think there is no other way to use.
so use script within body.

Javascript: Create a new div in <body> tag

This is going to be hard to explain but I will do my best. I want to write a Javascript function that takes two parameters (title, content) and creates a <div> tag in the <body> tag. The <div> tag should look like this.
<div>
<h2>title</h2>
<p>content</p>
</div>
My javascript code looks like this:
function addElement (title, content) {
var newDiv = document.createElement("div");
var newH2 = document.createElement("h2");
var title = document.createTextNode(header);
newH2.appendChild(title);
var p = document.createElement("p");
var post = document.createTextNode(entry);
p.appendChild(post);
newDiv.appendChild(newH2);
newDiv.appendChild(p);
// Missing codes here...
}
I dont know how to finish my method. Because of I have almost hundreds of tags inside my page and I want this new tags (when a user makes a new input) will appear on same place somewhere in the middle of the html code page in order to keep things organized.
If you would like to use jQuery take a look at this fiddle: http://jsfiddle.net/panpymq2/
In my fiddle I am binding to a button press. Then I call a method that appends new generated html to the body of the page. You can enter change where you are appending the new HTML with CSS3 selectors. just modify the $("insert selector there").append...
UPDATE
As per the new requirements I have updated my fiddle: http://jsfiddle.net/panpymq2/1/
I now prepend the new html to the document.
You already know how to add elements as children of other elements. That's what you used to add the h2 and p to the div. You could use the same appendChild to add the div to the document:
document.body.appendChild(newDiv);
But you don't want it at the bottom of the page--you want it "in the middle of the html code page". One straightforward way to do this is to add the newDiv to a container that's in the right place, in the middle of the page.
You'd first create this container in the page HTML:
<!doctype html>
<body>
<p>stuff before</p>
<div id="container"></div>
<p>stuff after</p>
</body>
Then, finish off addElement with:
document.getElementById('container').appendChild(newDiv);
One way would be if addElement took a third parameter which is the sibling/parent you want to insert your new element next to/within.
function addElement(title, content, target) {
...
target.insertAdjacentElement('afterend', newDiv);
// or
target.appendChild(newDiv);
}
I think this is as much of an HTML as a CSS problem. I've had the same issue.
One way of solving this problem is to make an (extra) container <div> as follows:
<div id="outer_container_elems">
<div id="inner_container_elems">
...
</div>
</div>
And append to inner_container_elems
Hope this helps!

jQuery "add" Only Evaluated When "appendTo" Called

this has been driving me crazy since yesterday afternoon. I am trying to concatenate two bodies of selected HTML using jQuery's "add" method. I am obviously missing something fundamental. Here's some sample code that illustrated the problem:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<p id="para1">This is a test.</p>
<p id="para2">This is also a test.</p>
<script>
var para1 = $("#para1").clone();
var para2 = $("#para2").clone();
var para3 = para1.add(para2);
alert("Joined para: " + para3.html());
para3.appendTo('body');
</script>
</body>
</html>
I need to do some more manipulation to "para3" before the append, but the alert above displays only the contents of "para1." However, the "appendTo appends the correct, "added" content of para1 and para2 (which subsequently appears on the page).
Any ideas what's going on here?
As per the $.add,
Create a new jQuery object with elements added to the set of matched elements.
Thus, after the add, $para3 represents a jQuery result set of two elements ~> [$para1, $para2]. Then, per $.html,
Get the HTML contents of the first element in the set of matched elements or set the HTML contents of every matched element.
So the HTML content of the first item in the jQuery result ($para1) is returned and subsequent elements (including $para2) are ignored. This behavior is consistent across jQuery "value reading" functions.
Reading $.appendTo will explain how it works differently from $.html.
A simple map and array-concat can be used to get the HTML of "all items in the result set":
$.map($para3, function (e) { return $(e).html() }).join("")
Array.prototype.map.call($para3, function (e) { return $(e).html() }).join("")
Or in this case, just:
$para1.html() + $para2.html()
Another approach would be to get the inner HTML of a parent Element, after the children have been added.

Jquery html() to div doesn't work

..I suppose because the html has script tags :-/
<script type="text/javascript">
$(document).ready(function() {
$('.ad_slot').html('<scr'+'ipt type="text/javascript"><!-- amazon_ad_tag = "xxxxxxxx-xx"; amazon_ad_width = "160"; amazon_ad_height = "600"; //--></scr'+'ipt>');
});
</script>
<div class="ad_slot"></div>
without the script tags the html displays fine. Is there any way to make this work with the tags included?
I need to generate a full js code using js for a project I'm working on.
I've also added the code to jsFiddle http://jsfiddle.net/c68wu/ although I'm not sure if scripts will show in the result window.
Script tags are going to be stripped out if you attempt to add them with html. Use
jQuery.getScript() instead.
Try to escape slash in the closing script tag:
$('.ad_slot').html('...<\/script>');
You'll need to escape the forward slashes:
$('.ad_slot').html('<scr'+'ipt type="text\/javascript"><!-- amazon_ad_tag = "xxxxxxxx-xx"; amazon_ad_width = "160"; amazon_ad_height = "600"; \/\/--><\/scr'+'ipt>');
Or this:
$('.ad_slot').html('<script type="text/javascript">amazon_ad_tag = "xxxxxxxx-xx"; amazon_ad_width = "160"; amazon_ad_height = "600";</script>');
I removed the HTML comment tags and the + in script tags. Oh yeah, and I removed the escaping on the slashes...not needed.
Also, you may want to look at when your script to generate the ads is being loaded and run. I suspect it's run before and never sees this code.

Categories

Resources