Changing document.write into the appropriate element.innerHTML - javascript

So, I'm new to learning js. And I know that document.write is outdated and the new solution is element.innerHTML. I'm working through some tutorial, but in testing my code it's breaking. What would be the appropriate means of going about inserting element.innerHTML and it's accompanying code, to get this to work?
Below is my snippet:
<!DOCTYPE html>
<html>
<head>
<title>8. Javascript Arrays</title>
</head>
<body>
<h1>8. Javascript Arrays</h1>
<script>
<div id="flightDate"></div>
<div id="myValues"></div>
var flightDate = new Date("September 22, 2004");
var myValues = ["Oceanic", 815, flightDate];
for (i in myValues)
{
document.write("<br />" + myValues[i]);
}
</script>
</body>
</html>

You can display the output in the DIVs that you created.
document.getElementById('flightDate').innerHTML = flightDate;
for (i = 0; i < myValues.length; i++) {
document.getElementById('myValues').innerHTML += myValues[i] + '<br/>';
}
+= concatenates the value with the content that's already there.

Related

trying to make randomised stats (of a RPG character) render in web browser (JavaScript)

Total JavaScript noob here. I am coding a character creation system in JavaScript. My problem is that I cannot get my randomised stats render in browser. I can get them render in console though. I have my .HTML file linked with my .JS file. I tried to find a answer to this but could not find it. Thank you.
const stats = ['Vitality','Strength', 'Agility', 'Dexterity', 'Wisdom', 'Charisma', ]
stats.forEach(function (item, index) {
console.log(item, Math.floor(Math.random() * 10) + 1)
})
I'm hoping this is the solution you're looking for.
Click the button "Run code snippet" to see it in action.
<html>
<head>
<title>Random Stats</title>
</head>
<body>
<h1>Stats</h1>
<div id="stats"></div>
<!-- NOTICE THIS AT THE BOTTOM OF THE BODY TAG -->
<!-- This is so it can load the page and find the dom element -->
<script type="text/javascript">
// 1. Create Your List
const stats = ['Vitality','Strength', 'Agility', 'Dexterity', 'Wisdom', 'Charisma'];
// 2. Choose the dom element you want to add to
const statsElement = document.querySelector('#stats');
// 3. Append stats for each to dom element
stats.forEach(function (item, index) {
// Notice the += to add to what already exists
statsElement.innerHTML += item + ":" + (Math.floor(Math.random() * 10) + 1) + "<br />";
});
</script>
</body>
</html>
Use "Run code snippet" to see how it looks like
const stats = ['Vitality','Strength', 'Agility', ];
const statsValues = {};
// Generate object what contains your values { 'Vitality': 4, 'Strength': 5 etc}
for (let i = 0; i < stats.length; i += 1) {
const nameStat = stats[i];
statsValues[nameStat] = Math.floor(Math.random() * 10) + 1;
}
// apply them to HTML
for (let i = 0; i < stats.length; i += 1) {
const nameStat = stats[i];
document.querySelector(`#${nameStat}`).innerHTML = `${nameStat}: ${statsValues[nameStat]}`;
}
// You can do it in one for, or in forEach if you like
<html>
<head>
<title>Random Stats</title>
</head>
<body>
<h1>Stats</h1>
<div id="Vitality"></div>
<div id="Strength"></div>
<div id="Agility"></div>
</body>
</html>

Google Feed API for RSS is not showing current events

I am attempting to use Google Feed API to display three current event listings for our homepage. This is to circumvent some of the issues we are having with a third part calendar application.
However, with the feed limit set to 3, the only listings that will show up for me are from Jan. 18. Is there a way to make the code show only current or future events?
Thanks in advance for any help.
HTML
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<meta charset="utf-8">
<title></title>
<script type="text/javascript" src="http://www.google.com/jsapi">
</script>
</head>
<body>
<div id="feed"></div>
</body>
</html>
JavaScript
google.load("feeds", "1");
var feedcontainer=document.getElementById("feed");
var feedurl="http://25livepub.collegenet.com/calendars/publishers-calendar-7.rss";
var feedlimit = 3;
var rssoutput = '';
function rssfeedsetup(){
var feedpointer=new google.feeds.Feed(feedurl);
feedpointer.setNumEntries(feedlimit) ;
feedpointer.load(displayfeed);
}
function displayfeed(result){
if (!result.error){
var thefeeds=result.feed.entries;
for (var i=0; i<thefeeds.length; i++){
var untrimContent = thefeeds[i].content;
var trimContent = untrimContent.split("<br>", 2);
rssoutput+="<div><a href='" + thefeeds[i].link + "'>" + thefeeds[i].title + "</a></div>" + trimContent;
feedcontainer.innerHTML=rssoutput;
}
} else {
feedcontainer.innerHTML = "Error Loading Events";
}
}
window.onload=function(){
rssfeedsetup();
};

Why do I lose formatting after running javascript?

This is probably a silly question but why do I lose all the formatting when the function test() starts? What should I change in my code? I would really appreciate your help!
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<style type="text/css">
body {
background: #E6E6FA;
font-family: book antiqua;
}
h1, h2 {
color: grey;
}
</style>
</head>
<h3>Title</h3>
<body bgcolor="#E6E6FA">
<input type="text" id="userInput"></input>
<button onclick="test()">Submit</button>
<p id="Demo"></p>
<p id="Beg"></p>
<p id="Fin"></p>
<script>
function test()
{
var nam= document.getElementById("userInput").value;
var l = nam.length;
var pocz = nam.slice(0,1);
var kon = nam.slice(-1);
document.getElementById("Demo").innerHTML = document.write("Your secret code: " + l + pocz + kon);
var one = nam.slice(-1)
if (one == "a") {
document.write(nam.slice(0,-1) + "bbb");
} else {
document.write(nam + "ccc");
}
}
</script>
</body>
</html>
If document.write is called after the DOM loaded, it replaces the document. Also you are using document.write incorrectly, it doesn't return anything. Just omit it and it will work fine.
document.getElementById("Demo").innerHTML = "Your secret code: " + l + pocz + kon;
For the other uses, do the same thing and assign the value to an element via innerHTML.
Please read the documentation before you use an unfamiliar function.
Never use document.write. Ever. Just don't use it. It is completely antiquated.
Felix Kling's answer will work for the first part, since you are assigning html to an element directly. but the later calls are adding more content to the document, not replacing content, so you must append new content to the document, or make another placeholder (like demo). here is how to do it with appending new content:
function test()
{
var nam= document.getElementById("userInput").value;
var l = nam.length;
var pocz = nam.slice(0,1);
var kon = nam.slice(-1);
document.getElementById("Demo").innerHTML = "Your secret code: " + l + pocz + kon;
var one = nam.slice(-1);
if (document.getElementsByClassName("spantext").length===0)
{
var text=document.createElement("span");
text.setAttribute("class","spantext");
document.getElementsByTagName("body")[0].appendChild(text);
}
else {
var text=document.getElementsByClassName("spantext")[0];
}
if (one == "a") {
text.innerHTML=nam.slice(0,-1) + "bbb";
} else {
text.innerHTML=nam + "ccc";
}
}
fiddle

Jquery .get not retrieving file

i have a code that is supposed to read from a html file, split it into an array and display parts of that array, but when going though with alert, i found that $.get is not actually getting the file
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
</head>
<body>
<button onclick="myfunction()">update</button>
<div id="div1"></div>
<script>
function myfunction() {
var info = "";
$.get("../Read_Test/text.html", function(data) {
SomeFunction(data);
});
alert(info);
var array = info.split("§n");
var people = array[1].split(",");
for (var i = 0; i < people.length; i++) {
document.getElementById("div1").innerHTML = people[i] + "<br>";
}
}
function SomeFunction(data) {
var info = data;
}
</script>
</body>
</html>
the directories are on a server and go like so:
Sublinks->Read_Test->This_File.html,text.html
The objective of this is that a file would have something along the lines of "a§nb1,b2,b3,§n" and the script would split it via "§n" then get "array[1]" and split that via ",". lastly it displays each part of that newly created array on a new line, so a file with "a§nb1,b2,b3,§n" would result in:
b1
b2
b3
Please help
Ajax is asynchronous, it make request and immediately call the next instruction and not wait for the response from the ajax request. so you will need to process inside of $.get. success event.
I have changed delimiter character to ¥. change same in text.html. problem was you have not mentioned character set to utf8 and due to this it could not recognized the special character and subsequently not able to split the string. i have aldo document type to HTML5.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<button onclick="myfunction()">update</button>
<div id="div1"></div>
<script>
function myfunction() {
$.get("../Read_Test/text.html", function(data) {
var info = data;
var array = info.split("¥");
var people = array[1].split(",");
for (var i = 0; i < people.length; i++) {
document.getElementById("div1").innerHTML += people[i] + "<br>";
}
});
}
</script>
</body>
</html>

How to add script code using javascript?

I want to add script tag using javascript, but I am not able to get it work. Below is code. I want to add this code in bigcommerce cart page.
var duration = document.getElementsByName("cartdata");
var cartstr = '<!-- MyBuys Page Parameters – Place in <body> element -->';
cartstr += '<script type="text/javascript">';
cartstr += 'mybuys.setPageType("SHOPPING_CART");';
cartstr += 'mybuys.set("email","consumer#example.com"); <!--consumer email can be blank if not known-->';
cartstr += 'mybuys.set("amount","99.34");';
for (var i = 0; i < duration.length; i++) {
str = duration[i].value;
var n = str.split('|');
cartstr += 'mybuys.addCartItemQtySubtotal("'+n[0]+'","'+n[1]+'","'+n[2]+'");'+'<br>';
}
cartstr += '</script>';
cartstr += '<!-- End MyBuys Page Parameters -->';
//alert(cartstr);
var script = document.createElement("script");
script.type = "text/javascript";
script.text = cartstr; // use this for inline script
document.body.appendChild(script);
I want below code added to page:
<!-- MyBuys Page Parameters – Place in <body> element -->
<script type="text/javascript">
mybuys.setPageType("SHOPPING_CART");
mybuys.set("email","consumer#example.com"); <!--consumer email can be blank if not known-->
mybuys.set("amount","99.34");
mybuys.addCartItemQtySubtotal("12345","1","54.34");
mybuys.addCartItemQtySubtotal("56789","3","45.00");
</script>
<!-- End MyBuys Page Parameters -->
This demonstrates how to dynamically add JavaScript:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
var optionalFunctionLoaded = false;
var commonFunction = function() {
console.log("test button clicked " + (new Date()).toLocaleString());
if (!optionalFunctionLoaded) {
// get optionalSrc e.g. via AJAX, eventually providing actual input values
var optionalSrc = 'function optFun(){console.log("optional function");}';
// if optionalSrc is not empty
var script = document.createElement("script");
script.innerHTML = optionalSrc;
document.head.appendChild(script);
optionalFunctionLoaded = true;
}
if(optionalFunctionLoaded) optFun();
}
</script>
</head>
<body>
<button id ="testButton">test</button>
<script type="text/javascript">
document.getElementById("testButton").onclick = commonFunction;
</script>
</body>
</html>
Tested with Firefox 24.0 / Linux.
The solution is to just add the code to the page:
<!-- MyBuys Page Parameters – Place in <body> element -->
<script type="text/javascript">
mybuys.setPageType("SHOPPING_CART");
mybuys.set("email","consumer#example.com"); <!--consumer email can be blank if not known-->
mybuys.set("amount","99.34");
mybuys.addCartItemQtySubtotal("12345","1","54.34");
mybuys.addCartItemQtySubtotal("56789","3","45.00");
</script>
<!-- End MyBuys Page Parameters -->
Why use JavaScript to put it there? Just add it to the page. You might have to adjust it a bit with your loop:
for (var i = 0; i < duration.length; i++) {
str = duration[i].value;
var n = str.split('|');
mybuys.addCartItemQtySubtotal(n[0],n[1],n[2]);
}
You should just be executing the code, there is no need to build the string. In the end, what you are trying to do is the same thing as running the code! Just execute it.
mybuys.setPageType("SHOPPING_CART");
mybuys.set("email","consumer#example.com");
mybuys.set("amount","99.34");
for (var i = 0; i < duration.length; i++) {
str = duration[i].value;
var n = str.split('|');
mybuys.addCartItemQtySubtotal(n[0],n[1],n[2]);
}
I don't know why would you want to do that. But if you really want to, here is a way you could try.
$('body').append("console.log('blah');")
OR
$('body').html($('body').html()+"console.log('blah');")
Replace console.log('blah') with your code
Note this is assuming you are using JQuery.
If not, you can still use Native Javascript to do something similar. Just search for creating an element and adding it to another using vanila javascript and you'll get lots of information on google.
Although, as epascarello says, its not a good idea to do this. Its basically a code smell and you can improve your code.
Hope this helps.

Categories

Resources