I am new to Javascript and am just playing around trying to print a simple for loop to the HTML.
HTML:
<div id="hello"</div>
JS :
var text="";
for (var i=0;i<10;i++) {
document.getElementById("hello").innerHTML=text+i;
}
My problem is that this code only outputs the last iteration '9', and not '0123456789' which is what I want.
Now if i do document.write it prints out the numbers fine but I heard this is bad practice so I just want to do it the correct way.
Thanks
It would be better to build your text content first and insert it into HTML element once (to save some time):
var text="";
for (var i=0;i<10;i++) {
text += i;
}
document.getElementById("hello").innerHTML = text;
You should use the addition assignment operator += that adds a value to a variable, so you're just missing + before = in :
document.getElementById("hello").innerHTML += text+i;
NOTE : Use textContent instead of innerHTML because you're appending just a text, check example bellow.
var text="";
for (var i=0;i<10;i++) {
document.getElementById("hello").textContent += text+i;
}
<div id="hello"></div>
Related
so I wrote a script to display 5 random arrays, but the page doesn't display anything.
here's the code:
<html>
<head>
<script>
function start(){
var arr(5),result;
result=document.getElementById("arraying");
result="<p>";
for(var i=0; i<5;i++){
arr[i]=Math.floor(Math.random()*10);
result+="arr["+i+"]= "+arr[i]+"</p><p>";
}
result+="</p>";
}
window.addEventListener("load",start,false);
</script>
</head>
<body>
<div id="arraying"></div>
</body>
</html>
I tried removing result=document.getElementById and write document.getElementById.innerHTML=result in the end of the function but didn't work. what's the error?
You cannot use the same variable for different purposes at the same time. First you assign a DOM element to result, and immediately on the next line you overwrite result with a string.
Build a string htmlStr inside your loop, and when that is done, assign this string to result.innerHTML property:
function start() {
let arr = [],
result, htmlStr = '';
result = document.getElementById("arraying");
htmlStr += "<p>";
for (let i = 0; i < 5; i++) {
arr[i] = Math.floor(Math.random() * 10);
htmlStr += "arr[" + i + "]= " + arr[i] + "</p><p>";
}
htmlStr += "</p>";
result.innerHTML = htmlStr;
}
window.addEventListener("load", start, false);
<div id="arraying"></div>
Looking at the code you seem to be missing some basic javascript concepts.
array size
This is probably your main issue:
var arr(5)
This does not make sense in javascript. Array length does not need to be predefined since all arrays are of dynamic length. Simply define an array like this:
var arr = []
Then later when you want to append new elements use push like this:
arr.push( Math.floor(Math.random()*10) )
adding html using innerHTML
There are different ways to dynamically inject html into your page. (It looks like) you tried to append the html as a string to the parent element. This is not possible.
You said you tried using innerHTML. That should work if used correctly.
A working implementation would work like this:
function start() {
var arr = []
var result = "<p>"
for(var i = 0; i < 5; i++) {
arr.push( Math.floor(Math.random()*10) ) // Btw this array isn't actually needed.
result += "arr[" + i + "] = " + arr[i] + "</p><p>"
}
document.getElementById("arraying").innerHTML = result
}
window.addEventListener("load", start, {passive: true});
adding html using createElement
A generally better way of dynamically adding html elements is via createElement.
This way you dont have to write html and are therefore less prone for making errors. It is also more performant and easier to integrate into javascript.
I think the best explaination is a commented implementation:
function start() {
var myDiv = document.getElementById("arraying") // get parent node
var arr = []
for(var i = 0; i < 5; i++) {
arr.push( Math.floor(Math.random()*10) )
var p = document.createElement("p") // create p element
p.innerText = "arr[" + i + "] = " + arr[i] // add text content to p element
myDiv.append(p) // append p element to parent element
}
}
window.addEventListener("load", start, {passive: true});
small tips
The let keyword works mostly the same as the var keyword, but is generally preferred because of some edge cases in which let is superior.
Fusing strings and variables using the plus operator is generally considered bad practice. A better way to do the string concatenation would have been
result += `arr[${i}] = ${arr[i]}</p><p>`
So I save my array as a variable: var arrayContents = contentData;
and my array: ['content_1', 'content_2', 'content_3', 'content_4']
So i've got my array, I then want to place it into my HTML which i've done via using text like such: $('.container').text(arrayContents);
I need to break my text up so it currently looks like:
And i'm trying to get it to look like :
How can I break my array up so each item drops onto a new line? As when I use .text I print the whole array as one not each separate item.
Use a foreach loop and add a <br> tag to go to next line:
var contentToInsert;
$.each(arrayContents,function(value){
contentToInsert += value + "<br>";
});
$('.container').html(arrayContents);
You need to use html() instead of text(), check this
var htm = '';
var arrayContents = ['content_1','content_2','content_3'];
arrayContents.forEach(function(item){
htm += item + '<br />'; // break after each item
});
$('.container').html(htm);
Actually .text() works with a string value. You passed an array, which leads the "engine" to call arrayContents.toString() to get a string from the array. As you can see there, this function separates each entry by a comma.
If you want to produce an output on one column, you have to generate HTML (as shown in this answer), or editing the div object through javascript DOM functions (fiddle) :
for (var i = 0; i < arrayContents.length; i++) {
var currentElement = document.createElement("DIV"); // "DIV" or block-type element
var currentText = document.createTextNode(arrayContents[i]);
currentElement.appendChild(currentText);
document.getElementById("container").appendChild(currentElement);
}
Be sure of what kind of HTML you want to produce.
I am attempting to write a script that will allow users to input numbers into a screen, add them to an array and then print the values on an innerHTML element.
However, when I attempt to use it in a for loop, nothing is printing out and it goes to a new page where the only thing displayed is the first number entered.
I am new at JavaScript and might be doing it incorrectly. Please let me know!
Thanks in advance
var a = [];
var count = 0;
function addNum() {
a[count] = document.getElementById('input').value;
count++;
}
function printValues() {
for (i = 0; i < a.length; i++) {
document.write(a[i], " ").innerHTML = array;
}
}
<input type="text" id="input">
<br>
<input type="button" onclick="addNum();" value="Add Number">
<br>
<input type="button" onclick="printValues();" value="Print Numbers">
<p>
<a id="array"></a>
</p>
From MDN:
Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open which will clear the document.
So your problem is caused by document.write. Once you write to your already loaded document, everything else is thrown away, including your javascript. (You had other problems too with just how you were using it, but this is the main problem).
You have an element with the id array, which I assume is where you want to put your numbers. So you need to get that element with getElementById and then set its innerHTML. You can use array.join to avoid the loop.
var a = [];
var count = 0;
function addNum() {
a[count] = document.getElementById('input').value;
count++;
}
function printValues() {
document.getElementById('array').innerHTML = a.join(",");
}
<input type="text" id="input">
<br>
<input type="button" onclick="addNum();" value="Add Number">
<br>
<input type="button" onclick="printValues();" value="Print Numbers">
<p>
<a id="array"></a>
</p>
A couple of other things you should look at. After adding a number in addNum, you should probably clear the text box by setting the value to null. Secondly, it's preferred to add event handlers in code rather than in your HTML.
function printValues() {
var strValues=''; // Initialize a temporary variable
for (i = 0; i < a.length; i++) {
strValues += a[i] + ' ';
}
document.write(strValues); //Writting variable to document.
}
In the above example we have create a temporary variable and sets the default value to blank. Then in for loop we concatenate the array value to variable using += sign.
What you are doing is not the correct way of setting stuff up in innerHTML . Also, you are not retaining the values to be printed on to the screen. Everytime , you click on print the new value inputted by the user is just getting passed and the old value is getting replaced with the new one . Here the variable valueToBePrinted will always remember the last value that was inputted as it concatenates all the inputted values to it, once the user is done with his/her input .
Look at the following piece of code :
var a = [];
var count = 0;
function addNum() {
a[count] = document.getElementById('input').value;
console.log(a[count]);
count++;
}
function printValues() {
var valueToBePrinted='';
for (i=0;i<a.length;i++) {
valueToBePrinted += a[i] + ' ';
console.log(valueToBePrinted)
document.getElementById('array').innerHTML =valueToBePrinted;
}
}
Also , look at the result in the Fiddle here : Fiddle
The statement "document.write(a[i], " ").innerHTML = array;" is wrong.
There is no variable named array declared in the code.
The correct form to print all the numbers using document.write is,
for (i=0;i<a.length;i++) {
document.write(a[i] + " ");
}
If you need sum of all input numbers and the print the sum, then you can simply sum it up in a variable as you click addNumber button as,
var total = 0;
function addNum() {
total += Number(document.getElementById('input').value);
}
function printValues() {
document.write(total);
}
You typically would not use a "count" variable to add items to an array but would instead push to the array however I kept it in case you needed it otherwise.
You would as others noted not do a document.write to an element but instead use the innerHTML and replace or append to that.
Odd also that you are putting the innerHTML in a link <a /> element but since that is what you are using I will reproduce that.
IF you do want to use these as number (integers?) you would want to parse them with parseInt(string, radix); or parsefloat.
You did not have i set as a variable object so I did that here
Slightly reworked code here:
var a = [];
var count = 0;
function addNum() {
a.push(parseInt(document.getElementById('input').value, 10));
count++;
}
function printValues() {
var i;
var myValues = "";
for (i = 0; i < a.length; i++) {
myValues = myValues + a[i] + " ";
}
var element = document.getElementById("array");
element.innerHTML = myValues;
}
Here is the code reproduced as a working example: http://jsfiddle.net/coffw8tg/
var html = {
easyBB :
['easybbtutorials','www.easybbtutorials.com','http://i76.servimg.com/u/f76/17/83/35/07/easybb10.png'],
AvacWeb:
['AvacWeb','www.avacweb.com','http://i45.servimg.com/u/f45/16/35/08/55/new_lo12.png'],
easyBB2:
['easybbtutorials','www.easybbtutorials.com','http://i76.servimg.com/u/f76/17/83/35/07/easybb10.png'],
AvacWeb2 :
['AvacWeb','www.avacweb.com','http://i45.servimg.com/u/f45/16/35/08/55/new_lo12.png'],
easyBB3 :
['easybbtutorials','www.easybbtutorials.com','http://i76.servimg.com/u/f76/17/83/35/07/easybb10.png'],
AvacWeb3 :
['AvacWeb','www.avacweb.com','http://i45.servimg.com/u/f45/16/35/08/55/new_lo12.png']
};
var cont = document.getElementById('container');
for(var key in html){
for(var i =0;i<key.length;i++ ){
var name= '<span class="name">'+html[key][0] +'</span>',
link = '<span class="url">'+html[key][1] +'</span>',
image = '<img src="'+html[key][2]+'" title="'+html[key][0]+'" />';
cont.innerHTML= '<div class="wrapper">'+ name + '<br />'+image+'<br />'+link+'</div>';
i++;
}
}
I am trying to iterate over the arrays in each key of the HTML object I created problem is not sure how to do this I've tried multiple ways now and I believe (since I am posting) I am doing this all wrong. I've also tried doing: html[key[i]][0] though of course I get an error of i is not defined. Any suggestions what I am doing wrong, as of right now it is only posting one array to the html.
The problem is not the iteration, it's the line
cont.innerHTML = ...
which is replacing the content each time the loop iterates so that you only see the final item ("AvacWeb3").
Change that to
cont.innerHTML += ...
and get rid of the for (var i =0 ... loop which isn't needed. (jsfiddle)
for(var i = 0; i < html[key].length; i++){
...
You should do html[key][i][0].
And also you should do what Trevor said, html[key].length instead of key.length.
Make yourself easy by assigning html[key] to var currentkey for example, easier to keep track on.
Also, look into array.forEach, just for fun ;)
Im trying to add an array to a webpage. I have tried a few different pieces of code show below but none of them work. I would like the output to be similar to a list like:
text1
text2
text3
...
The code I have used so far is:
var i;
var test = new Array();
test[0] = "text1";
test[1] = "text2";
test[2] = "text3";
// first attempt
$('#here').html(test.join(' '));
// second attempt
$(document).ready(function() {
var testList="";
for (i=0;i<test.length; i++) {
testList+= test[i] + '<br />';
}
$('#here').html('testList');
songList="";
});
I am quite new to javaScript so I am not sure if I have just made a small mistake or if Im doing this in the wrong way. Also, above is a copy of all the code in my javaScript file and some places online are saying I need to import something? Im not sure!
Thanks
Try without quotes:
$('#here').html(testList);
-or-
$('#here').html(test.join('<br />'));
Another approach:
var html = ''; // string
$.each(test,function(i,val){ // loop through array
var newDiv = $('<div/>').html(val); // build a div around each value
html += $('<div>').append(newDiv.clone()).remove().html();
// get the html by
// 1. cloning the object
// 2. wrapping it
// 3. getting that html
// 4. then deleting the wrap
// courtesy of (http://jquery-howto.blogspot.com/2009/02/how-to-get-full-html-string-including.html)
});
$('#here').html(html);
There might be more code in the latter, but it'll be cleaner in the long run if you want to add IDs, classes, or other attributes. Just stick it in a function and amend the jQuery.
Try changing the line
$('#here').html('testList')
to
$('#here').html(testList)
What you have works if you remove the single quotes from testList. However, if you would like an actual unordered list you can do this. (here's a jsFiddle)
var test = new Array();
test[0] = "text1";
test[1] = "text2";
test[2] = "text3";
// first attempt
$('#here').html(test.join(' '));
// second attempt
$(document).ready(function() {
var testList=$("<ul></ul>");
for (var i=0;i<test.length; i++) {
$(testList).append($("<li></li>").text(test[i]));
}
$('#here').html(testList);
songList="";
});
This line:
$('#here').html('testList');
shouldn't have single quotes around testList - you want to use the content of the variable, not the string literal "testList".
Don't pass the variable as a string : $('#here').html('testList'); Pass it without quotes : $('#here').html(testList);
Here's the simplest version:
$(document).ready(function() {
var test = ["text1", "text2", "text3"];
$('#here').html(test.join("<br>"));
});