How can I make a simple table row with numbers using .appendChild? - javascript

I'm a beginning programmer and I wondered if someone could help me.
I want to get a table with a row and 7 numbers in table data & making the function react. I tried this but it doesn't work, and I've been looking for some time at it now:
<html>
<head>
<script type="text/javascript">
function maaktable () {
alert("Hey!");
var tabdata
= tabrow.appendChild(document.createElement("td").innerText
= amount[i];
var tabrow = tablestart.appendChild(document.createElement("tr");
var tablestart = document.createElement("table");
tablestart;
tabrow;
for (i = 0; i < 6; i++) {
tabdata;
}
}
</script>
</head>
<body>
<button onclick="maaktable()">Begin</button>
</body>
</html>
The problem is it doesn't even alert. What can i do to make this work?

well not sure if this is the intended result but your code does look a little off
this should at least get the alert to show and hopefully get you on the right track
function maaktable () {
alert("Hey!");
var tablestart = document.createElement("table");
var tabrow = tablestart.appendChild(document.createElement("tr"));
for (i = 0; i < 6; i++) {
//tabdata;
tabrow.appendChild(document.createElement("td").innerText(amount[i]));
}
}

Related

Creating HTML list using loop in Javascript

I've got an array in Javascript that I want to print to screen which is: (my function for ro[j] is simplified in this example, but that doesn't matter)
<div class="result2"></div>
<script>
var j;
var ro = [0];
for(j=0; j <= 49; j++){
ro[j] = j;
$('.result2').html(ro[j]);
}
</script>
But this doesn't work as I think it keeps replacing the div with each loop rather than adding to the div. Is there a good way to implement this? I thought you could try something like this:
<div class="result2"></div>
<script>
var j;
var ro = [0];
for(j=0; j <= 49; j++){
ro[j] = j;
if(j==0){
$('.result2').html(ro[j]);
}else{
var res = $('.result2').val();
$('.result2').html(res + ro[j]);
}
}
</script>
but this doesn't work since you can't seem to call the result of the script midway through the script? Or I just made a mistake, I'm not sure. Any help would be great!
edit: forgot a semicolon
A list element (ul or ol) should be used for lists as it's more semantically correct:
<ul id="result2"></ul>
Using es6 syntax you can append elements to that list like this:
const ro = [...Array(49).keys()]; // Just setting up a sample array
for (r of ro) {
let li = document.createElement('li');
li.innerHTML = r;
document.getElementById('result2').appendChild(li);
}
This will place the numbers vertically in the screen.
<!DOCTYPE HTML>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="result2"></div>
<script type='text/javascript'>
var ro = [];
for (var j = 0; j <= 49; j++) {
ro.push(j);
$('.result2').append(ro[j] + '<br />');
}
</script>
</body>
</html>

Unexpected hidden div appears in html file

I have been trying to search this, but haven't even found anyone with the same problem.
For my assignment, I had to write a javascript code that would read all the text from the external page (from the same directory though), but that's not the problem. The problem appeared when I have created a test html file with some random text.
HTML Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
<p> Just a random text.</p>
<h1> More of a random text</h1>
<p> And again, just testing the program.</p>
</body>
</html>
And this code is taken from the debugger:
Image of html file as from Inspector
The problem is my javascript code does read the text from this div element and append the array of words that i have.
Does anyone know why is this div generated and how to get rid of it ?
P.S I have tried creating other html files, but div appears there too.
Thanks in advance!
EDIT:
That's my JS code:
var externalPage;
var words = [];
var j = 0;
function indexOf(array, item) {
for (var i = 0; i < array.length; i++) {
if (array[i][0].toString() === item.toString()) return i;
}
return -1;
}
function clearNode(node) {
while (node.firstChild) {
node.removeChild(node.firstChild);
}
}
function sortNumerically(words) {
return words.sort(function(a,b){
return b[1] - a[1];
});
}
function sortAlphabetically(words) {
return words.sort();
}
function openFile(url) {
externalPage = window.open();
externalPage.location = url;
}
function extractWords(node) {
if (node.nodeType==Node.ELEMENT_NODE) {
for (var m = node.firstChild; m!=null; m = m.nextSibling)
extractWords(m);
}
else {
var value = node.nodeValue.trim();
value = value.split(/\s/);
for(var i = 0; i < value.length; i++) {
if(indexOf(words, value[i]) != -1) {
words[indexOf(words, value[i])][1] =
words[indexOf(words, value[i])][1] + 1;
} else if(value[i] != '') {
words.push([]);
words[j][0] = value[i];
words[j][1] = 1;
j++;
}
}
}
}
function populateTable(arr) {
var tbody = document.createElement('tbody');
clearNode(tbody);
for(var i = 0; i< words.length; i++) {
var tr = document.createElement('tr');
var tdW = document.createElement('td');
var tdF = document.createElement('td');
tdW.appendChild(document.createTextNode(arr[i][0]));
tdF.appendChild(document.createTextNode(arr[i][1]));
tr.appendChild(tdW);
tr.appendChild(tdF);
tbody.appendChild(tr);
}
document.getElementById('tableCounter').appendChild(tbody);
}
function generateArray(node) {
words = [];
j = 0;
extractWords(node, words);
alert(sortNumerically(words));
populateTable(words);
}
This hidden box is an effect of a virus. The page dataloading.net is know as a virus page. You can search for it with your favourite search-module (google, bing, ...).
As attached code snap that DIV definitely come from JS or any JS plugin which simply append to body with generated code.

change HTML code for fading background replacing images

This is my HTML code:
<html>
<head>
<script language="JavaScript">
<!--
// Set speed (milliseconds)
var speed = 4000
// Specify the image files
var Pic = new Array() // don't touch this
// to add more images, just continue
// the pattern, adding to the array below
Pic[0] = 'img_1.jpg'
Pic[1] = 'img_2.jpg'
Pic[2] = 'img_3.jpg'
Pic[3] = 'img_4.jpg'
// =======================================
// do not edit anything below this line
// =======================================
var t
var j = 0
var p = Pic.length
var preLoad = new Array()
for (i = 0; i < p; i++){
preLoad[i] = new Image()
preLoad[i].src = Pic[i]
}
function runBGSlideShow(){
if (document.body){
document.body.background = Pic[j];
j = j + 1
if (j > (p-1)) j=0
t = setTimeout('runBGSlideShow()', speed)
}
}
//-->
</script>
</head>
<body onload="runBGSlideShow()">
</body>
</html>
I tried everything I know to change it so the pictures will fade when replacing but I didn't succeed.
If you can I will appreciate it if you will add to the HTML code (if can't it's ok to add css )
Please look and see if you can help me.
Why reinvent the wheel?
There's a beautiful jQuery plugin that does this already
http://srobbin.com/jquery-plugins/backstretch/

AJAX and JQuery to regularly load page

I'm trying to automatically show stock results from an external page, using jquery and ajax. I changed my original file to make it simpler. Sadly, it is not working again.. Can anyone see what my problems are? Thank you so much!
HTML:
<!DOCTYPE HTML>
<html>
<head>
<title>Stocks</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<script src="projectstocks.js"></script>
</head>
<body>
<div>
<content id="content">
</content></div>
</body>
</html>
projectstocks.js:
window.onload = function() {
var stocks = [];
var content = document.getElementById("content");
update();
setInterval("getData()", 1000);
}
function getData(data) {
content.innerHTML = "";
var tbod = document.getElementById("stocks");
var myTable= "<table id='table' border='1'>";
for(var i = 0; i < data.length; i++) {
var tr = document.createElement('tr');
var obj = data[i];
for(key in obj){
console.log(key);
var value=(obj[key]);
console.log(value);
content.innerHTML += ("<tr><td>");
content.innerHTML += ((obj[key]));
content.innerHTML += ("<br><br></td></tr>");
}
}
myTable+="</table>";
}
function update() {
$.getJSON('http://shodor.org/~amalani/AjaxTutorial/stocks/stocks.php?symbols=GOOG+CAT+FB', getData);
}
Thanks again! This doesn't have to be very fancy, let me know if there's anything I don't need.
You are trying to write the results to these elements which do not exist in your html:
document.getElementById("stocktable").innerHTML = table;
var d = new Date();
document.getElementById("date").innerHTML = "Last Update: " + d.toLocaleString();
add
<div id="stocktable"></div>
<div id="date"></div>
to your html.

JavaScript - need help combining two scripts.

I’m trying to call a user input array.
I’m very new on Javascript but know I somehow need to reference the array (it is somewhere where I put the ???).
<script>
var arrayX =5;
var arrayY =1;
var array=new Array(arrayX);
var planetIndex=0;
for (x=0; x<array.length; x++)
{array [x] = new Array(arrayY);}
function insert(val1){
array[planetIndex][0]=val1;
planetIndex++;
document.getElementById('name').value = ''; };
function worldChange() {
var newplanet = ????????????
var whichWorld = Math.floor(Math.random()*newplanet.length);
return planetIndex[whichWorld];
var planets = document.getElementsByClassName("world-name")
for (var i=0; i < planets.length; i++) {
planets[i].innerHTML = worldChange();};
};
</script>
<body>
<div>
<form>
<input type="integer" id="name"/>
<input type="button" value="Add Planets" onclick="insert (this.form.name.value);"/>
</form>
<input type="button" value="See planet!" onClick="worldChange()" />
<br> Hello <span class="world-name">Earth!</span><br />
</div>
</body>
I got both elements of the script to work perfectly on my site so every time someone hits a button it changes the guy in the story. But as you see if pulls from the array I created. I want to pull from an array that a user creates so they could input their own list of names.
so this script works fine:
function newGuy() {
var guys = new Array ("Jeff", "Mike", "George", "Harold");
var whichGuy = Math.floor(Math.random()*guys.length);
return guys[whichGuy];}
var guy = document.getElementsByClassName("guy")
for (var i=0; i < guy.length; i++) {
guy[i].innerHTML = newGuy();}
And this script works alone:
var arrayX =5;
var arrayY =1;
var array=new Array(arrayX);
var guyIndex=0;
for (x=0; x<array.length; x++)
{array [x] = new Array(arrayY);}
function insert(val1){
array[guyIndex][0]=val1;
guyIndex++;
document.getElementById('name').value = ''; };
Just baffled on how to put them together.
There are a lot of problems with your script but to give you an idea on how to get it to work :
var planets = [];
// define how many planets there will be initially
var initialLength = 5;
// add the initital planets
for (x = 0; x < initialLength; x++) {
planets.push("planet" + x);
}
function insert() {
var planetToInsert = document.getElementById('name').value;
if (planetToInsert) {
// add the input to the array of planets
planets.push(planetToInsert);
document.getElementById('name').value = '';
} else {
alert("please enter a value");
}
}
function worldChange() {
// randomly pick an index
var whichWorld = Math.floor(Math.random() * planets.length);
document.getElementById('world-name').innerHTML = planets[whichWorld];
}
working sample here
For finding problems in you code jsFiddle can be of excellent help. Run JSlint to find the basic errors, put in alerts as poor mans debugging.
For a good javascript book I would recommend javascript patterns

Categories

Resources