Creating HTML list using loop in Javascript - 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>

Related

How not to make <br> a tag

<script>
var y="<br>"
function repeater(num){
for (var i=0;i<num;i++)
{document.write(y) }
}
document.write(repeater(4))
</script>
My goal is to make the tag appear
4 times, not the actual breaks. The result shows undefined.
Since the question is asking for Javascript solution not JQuery (since no jQuery tags), I'll add the answer using Javascript.
<script>
var y = "<br>"
function repeater(num) {
for (var i=0; i < num; i++) {
document.body.innerText += y;
}
}
repeater(4);
</script>
or maybe you need to set a text into the spesific element (<div id="app"><div>)? no problem, we can improve the code a little bit.
<script>
var y = "<br>"
function repeater(el, num) {
for (var i=0; i < num; i++) {
el.innerText += y;
}
}
var el = document.getElementById('app');
repeater(el, 4);
</script>
<script>
var res = "";
var y="<br>";
function repeater(num){
for (var i=0;i<num;i++) {
res = res + y;
}
$('#customDiv').text(res);
}
(repeater(4))
You can put a custom <div id="customDiv"></div> inside your html file.

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.

SyntaxError: invalid flag after regular expression and white screen

I can't figure out why my page will not work. It just gives me a white screen when I try to load it. Is there a code I am missing? I don't know if my spaces matter either. Here is my code:
<!DOCTYPE html>
<html>
<head><body>
<title>Initializing an Array</title>
<style type="text/css">
table {width:10em}
th {text-align:left}
</style>
<script language="JavaScript">
<!--
{//create (declare) two new arrays
var n1=new Array(5); //allocate five-element Array
var n2=new Array (); //allocate empty Array
//assign values to each element of Array n1
for ( var i = 0; i <n1.length; ++i )
n1[ i ] = i;
//create and initialize five elements in Array n2
for ( i=0; i <5; ++i )
n2[ i ] = i;
outputArray("Array n1:",n1);
outputArray("Array n2:",n2);
//output the heading followed by a two-column table
//containing subscripts and elements of "theArray"
function outputArray (heading,theArray)}
{
document.writeln("<h2>"+heading+"</h2>");
document.writeln("table border=\"1\"");
document.writeln("<thead><th>Subscripts</th>"+"<th>Value</th></thead> <tbody>");
//output the subscript and value of each array element
for ( var i = 0; i <theArray.length; i++ )
document.writeln("<tr><td>+i+"</td><td>"+theArray[i]+"</td></tr>");
document.writeln("/tbody></table>");
} //end function outputArray
//-->
</script>
</head></body>
</html>
Please help! Thanks.
You have broken HTML and invalid Javascript.
<script language="JavaScript">
For your DOCTYPE of html, there is no need to specify any attributes to a <script> tag except src, and that is only needed if you are loading an external script file. And there is no attribute language. You likely meant type="text/javascript" but that is the default and therefore redundant.
<!--
You can't have HTML comments inside a <script> block. You are telling the browser that what is inside the <script> block is Javascript, then you putting invalid javascript. There will likely be errors displayed in the console.
Your example, tidied up, would look something like this:
<script>
// create (declare) two new arrays
var n1 = new Array(5); //allocate five-element Array
var n2 = new Array(); //allocate empty Array
// assign values to each element of Array n1
for (var i = 0; i < n1.length; ++i) {
n1[ i ] = i;
}
// create and initialize five elements in Array n2
for (i=0; i < 5; ++i) {
n2[ i ] = i;
}
outputArray("Array n1:",n1);
outputArray("Array n2:",n2);
// output the heading followed by a two-column table
// containing subscripts and elements of "theArray"
function outputArray (heading, theArray) {
var html = '<h2>' + heading + '</h2>';
html += '<table border="1">';
html += '<thead><th>Subscripts</th><th>Value</th></thead>';
html += '<tbody>';
// output the subscript and value of each array element
for (var i = 0; i < theArray.length; i++) {
html += '<tr><td>' + i + '</td><td>' + theArray[i] + '</td></tr>';
}
html += '</tbody></table>';
var div = document.createElement('div');
div.innerHTML = html;
document.body.appendChild(div);
}
</script>
You forgot quote " and on the next line < in </tbody> in last for loop.
document.writeln("<tr><td>"+i+"</td><td>"+theArray[i]+"</td></tr>");
^
document.writeln("</tbody></table>");
^
Of course nothing gets displayed, the base HTML layout is completely wrong.
You wrote :
<head>
<body>
(all the stuff)
</head>
</body>
It should be :
<head>
(scripts.....)
</head>
<body>
(HTML....)
</body>

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

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]));
}
}

How do I create n canvases from within Javascript?

I am looking for a way to create canvases as I need them at run time. my code so far is
var isCanv = new Array();//bool array for which places in the arrays are/are not in use
var canv = new Array();//for the canvases
var ctx = new Array();//for the contexts
var inhtml = new Array();//for the html canvas tags for each canvas
var upperBound = -1;//the highest index used so far
function createCtx(){
var i = 0;
while(isCanv[i]){
i++;
}
inhtml[i] = '<canvas id="canv'+i+'" width="'+800+'px" height="'+800+'px" style="display:block;background:#ffffff+;"></canvas>';
isCanv[i] = true;
if(i>upperBound){
upperBound = i;
}
var tohtml = '';
for(var j = 0; j<= upperBound; j++){
if(isCanv[i]){
tohtml+=inhtml[j];
}
}
document.getElementById('game').innerHTML=tohtml;
canv[i] = document.getElementById('canv'+i);
ctx[i] = canv[i].getContext('2d');
return(i);
}
function keyEvent(event) {
var i = 0;
while(isCanv[i]){
ctx[i].fillStyle="#00FFFF";
ctx[i].fillRect(0,0,800,800);
i++;
}
}
and the html looks like this
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>redicated</title>
</head>
<body style="background:#333333;" onkeydown="keyEvent(event)">
<div id="game"></div>
<script src="game.js"></script>
</body>
</html>
This works for the first canvas, but any subsequent addition breaks it all.
Does anyone know how I could fix this, or of a better way of doing it?
Edit:
I figured it out. I need to recreate the context every time there is an addition. now my code looks like
function createCtx(){
var i = 0;
while(isCanv[i]){
i++;
}
inhtml[i] = '<canvas id="canv'+i+'" width="'+800+'px" height="'+800+'px" style="display:block;background:#ffffff+;"></canvas>';
isCanv[i] = true;
if(i>upperBound){
upperBound = i;
}
var tohtml = '';
for(var j = 0; j<= upperBound; j++){
if(isCanv[j]){
tohtml+=inhtml[j];
}
}
document.getElementById('game').innerHTML=tohtml;
for(var j = 0; j<= upperBound; j++){
if(isCanv[j]){
canv[j] = document.getElementById('canv'+j);
ctx[j] = canv[j].getContext('2d');
}
}
return(i);
}
The for loop:
for(var j = 0; j<= upperBound; j++){
if(isCanv[i]){
tohtml+=inhtml[j];
}
is only ran once since when it is first executed j == upperBound. To fix this try removing
if(i>upperBound){
upperBound = i;
}
and whats the point of upperBound anyways it will always be equivalent to i so why not just use that.

Categories

Resources