Why doesn't my for loop execute? - javascript

When i use document.write it works, but it doesn't work with getElementById.
The same for while.
`
<div id="mydiv"></div>
<script>
var i = 0;
for (i=0; i<=10; i++){
//while (i<=10){
document.getElementById("mydiv").innerHTML = i + "<br>";
//i++;
}
</script>
Output is just 10, but I want to list 0-10 line by line. How to fix?

Each time your loop ran, it overwrite innerHTML for the div.
This implementation starts with an empty string for html, then uses += to concatenate the counter and <br> on each iteration.
var i = 0;
var html = '';
for (i=0; i<=10; i++){
html += i + '<br>';
}
document.getElementById("mydiv").innerHTML = html;

You are over-writing or replacing the contents. You need to append, so you can use += operator instead of =.
<div id="mydiv"></div>
<script>
var i = 0;
for (i=0; i<=10; i++){
document.getElementById("mydiv").innerHTML += i + "<br>";
}
</script>

You're overwriting. Append instead.
for (var i = 0; i <= 10; i++) {
var div = document.getElementById("mydiv");
div.innerHTML = div.innerHTML + "<br/>" + i;
}
<div id="mydiv"></div>

While other answers are true, I think it's a risky practice because your browser might try to execute the code before having loaded all html elements. (For example if your div is after the code..)
So I propose this:
<div id="mydiv">
<script>
for (var i=0; i<=10; i++){
document.write ( i + "<br />");
}
</script>
</div>
N.B: However, keep in mind you cannot use "document.write" after the page finished loading.
You can also do that to be safe:
<div id="mydiv"></div>
<script>
document.onload = function(){
temp=""
for (var i=0; i<=10; i++){
temp += i + "<br />";
}
document.getElementById("mydiv").innerHTML = temp;
}
</script>

Related

Print text on HTML from JavaScript

I have this for loop
<script>
...
for(i = 0;i < json.length;i++){
document.getElementById("pText").innerHTML = json[i].name;
document.getElementById("pLink").setAttribute("href",json[i].html_url);
}
</script>
I want to print a paragraph with a href on each loop, so i did this:
</script>
<a id="pLink">
<p id="pText">
</p>
</a>
It works but the thing is this only prints the last loop.
So i tried this inside the script
document.write("<a href=\"" + json[i].html_url + "\">");
document.write("<p>" + json[i].name + "</p>");
document.write("</a>");
instead of this:
document.getElementById("pText").innerHTML = json[i].name;
document.getElementById("pLink").setAttribute("href",json[i].html_url);
And it prints everything i want but it replaces the whole page.
How can i do this? Do i need to create an id for every loop? Like "pText1, pText2, etc.
Create a container element for that loop, and add the html as you had in mind
<div id="container"></div>
Then in javascript
var container = document.getElementById('container');
var my_html = '';
for(var i = 0;i < json.length;i++){
my_html += '<a href="' + json[i].html_url + '\">';
my_html += '<p>'+ json[i].name + '</p>'
my_html += '</a>'
}
container.innerHTML = my_html;
What we are doing here is adding the content to a string as many times as needed and then add it to the container so it already has all the loops
document.getElementById("pText").innerHTML = json[i].name;
document.getElementById("pLink").setAttribute("href",json[i].html_url);
If you want to use your this code, you have to write "+=" instead of the "=".
var json = [
{"name":"Name 1", "html_url": "http://www.example.com"},
{"name":"Name 2", "html_url": "http://www.example.com"},
{"name":"Name 3", "html_url": "http://www.example.com"}
];
for(var i = 0; i < json.length; i++){
document.getElementById("pText").innerHTML += json[i].name + "<br>";
document.getElementById("pLink").setAttribute("href",json[i].html_url);
}
<a id="pLink">
<p id="pText">
</p>
</a>
I will do it in the following way:
let json = [{'name':'Google','html_url':'https://www.google.com/'}, {'name':'Facebook','html_url':'https://www.facebook.com/'}, {'name':'Twitter','html_url':'https://twitter.com/?lang=en'}];
let item = document.querySelector(".pLink")
for(let j = 1; j<json.length; j++){
let cln = item.cloneNode(true);
document.body.appendChild(cln);
}
let aTag = document.querySelectorAll('a.pLink');
aTag.forEach(function(item, i){
let a = item.setAttribute("href",json[i].html_url);
let p = item.querySelector('.pText');
p.innerHTML = json[i].name;
})
<a class="pLink">
<p class="pText">
</p>
</a>

Looping inside a string in JavaScript

How does a loop work in a string like this?
var w = window.open('','','width=792,height=612');
$(w.document.body).html('<div>'+
'<ul>' +
for(var i=o; i<=10; i++){
'<li>'+ i +'</li>'+
}
'</ul>'+
'</div>');
I highly suggest you create your string before inserting it into your table.
$(document).ready(function(){
var w = window.open('','','width=792,height=612');
var myString = "";
for(var i=0; i<=10; i++){
myString += "<tr><td>hello</td></tr>";
}
$('body').html('<table>' + myString + '</table>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
</body>
I also corrected a lot of your code since there was a few error, ex: var i = o instead of i = 0.

javascript array to html <li>

I got an array from json and I need to put each item in a <li> on my html
something like this :
names : {john, paul, ringo,george}
into <li>john</li>..
my code:
<div id="demo"></div>
script:
function onLocationsReceived(data) {
console.log("recievd");
for (var i = 0; i < data[0].Sensors.length; i++) {
var sensorNames = data[0].Sensors[i].Name;
document.getElementById("demo").innerHTML = sensorNames;
console.log(sensorNames);
}
}
on the concole.log it prints just fine..
document.getElementById("demo").innerHTML = '<li>' + sensorNames '</li>
something like that???
Using something like below
function onLocationsReceived(data){
var html="";
for (var i = 0; i < data[0].Sensors.length; i++) {
var sensorNames = data[0].Sensors[i].Name;
html+="<li>"+sensorNames+"</li>";
console.log(sensorNames);
}
document.getElementById("demo").innerHTML=html;
}
You can use syntax below
document.getElementById('demo').innerHTML ='<li>' + sensorNames + '</li>'
You should cache the iterative sensorNames into a var with the li and then replace the innerHTML:
var content = "",
sensorNames;
for (var i = 0; i < data[0].Sensors.length; i++) {
sensorNames = data[0].Sensors[i].Name;
content += "<li>" + sensorNames + "</li>";
}
document.getElementById("demo").innerHTML = content;

document.getElementById.innerHTML does not write anything ..?

My Problem:
document.getElementById("values").innerHTML does not write anything. If I try to do document.getElementById("values").innerHTML = "stuff"; (just with a String) - nothing happens.
What am I doing wrong here?
HTML:
<form onsubmit="save_entry();return false;">
<label for="i_km">Kilometer: <input type="text" name="km" id="i_km"></label><br>
<label for="i_fuel">Sprit: <input type="text" name="fuel" id="i_fuel"></label><br>
<input type="submit" value="Save" />
</form>
<div id="values"></div>
JavaScript:
function save_entry() {
var anzahl = localStorage.length/2;
var nameKeyKm = "k" + anzahl;
localStorage.setItem(nameKeyKm,document.forms[0]["km"].value);
var nameKeyF = "F" + anzahl;
localStorage.setItem(nameKeyF,document.forms[0]["fuel"].value);
document.write("Entry saved!")
}
function show_entry() {
document.getElementById("values").innerHTML = "<table><th>Kilometers</th><th>Tanked</th>";
for (var i = 0; i < localStorage.length/2; i++) {
alert("d");
var temp_km = "k"+i;
var temp_f = "F"+i;
document.getElementById("values").innerHTML = "<tr>";
document.getElementById("values").innerHTML = "<td>"+localStorage.getItem(temp_km)+"</td>";
document.getElementById("values").innerHTML = "<td>"+localStorage.getItem(temp_f)+"</td>";
document.getElementById("values").innerHTML = "</tr>";
}
document.getElementById("values").innerHTML = "</table>";
}
show_entry();
This does work!
function show_entry(){
var content = '';
content = content + '<table><th>Kilometer</th><th>Getankt</th>';
for(var i = 0; i < localStorage.length/2; i++)
{
var temp_km = "k"+i;
var temp_f = "F"+i;
content = content + "<tr>";
content = content + "<td>"+localStorage.getItem(temp_km)+"</td>";
content = content + "<td>"+localStorage.getItem(temp_f)+"</td>";
content = content + "</tr>";
}
content = content + "</table>";
document.getElementById("values").innerHTML = content;
}
innherHTML is an attribute, so everytime you write document.getElementById('id').innerHTML = '...' you are actually changing the value of innerHTML to that thing, not concatenating it.
So writing document.getElementById("values").innerHTML = "<table><th>Kilometers</th><th>Tanked</th>"' changes the value of innerHTML to "<table><th>Kilometers</th><th>Tanked</th>"', and, afterwards, you replaced this value for <tr>, then for <td>...</td> and so on...
You clearly want to create a table. Therefore, you should be concatenating the strings, using +=, like this:
function show_entry() {
document
.getElementById("values")
.innerHTML = "<table><th>Kilometers</th><th>Tanked</th>";
for(var i = 0; i < localStorage.length/2; i++)
{
var temp_km = "k"+i;
var temp_f = "F"+i;
document.getElementById("values").innerHTML += "<tr>";
document.getElementById("values").innerHTML += "<td>"+localStorage.getItem(temp_km)+"</td>";
document.getElementById("values").innerHTML += "<td>"+localStorage.getItem(temp_f)+"</td>";
document.getElementById("values").innerHTML += "</tr>";
}
document.getElementById("values").innerHTML += "</table>";
}
show_entry();
Each time you do
document.getElementById("values").innerHTML = "...";
you will replace the html inside the div with ID 'values'
So calling it multiple times with different values doesn't make sense.
You would either call it once and setting the whole innerHTML at once, like this
document.getElementById("values").innerHTML = "<tr><td>....etc...</td></tr>";
If you would call innerHTML sequentially you would do it as follows (which is just how to append any string in javascript), but in the comments below I just learned this should not be done like this:
document.getElementById("values").innerHTML += "<tr>";
document.getElementById("values").innerHTML += "<td>"+localStorage.getItem(temp_km)+"</td>";
document.getElementById("values").innerHTML += "<td>"+localStorage.getItem(temp_f)+"</td>";
document.getElementById("values").innerHTML += "</tr>";

Rolling through an array with jQuery, HTML & JavaScript

I wanted to print this array: photolist into my DIV called: fotolist, but don’t know how to. I want to print the array after it loops through both completely. How do I do this?
<!DOCTYPE html>
<html>
<head>
<script src="jquery-min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
API_KEY = 'YOURAPIKEY'; //INSERT API KEY
USER_ID = '22694125#N02'; //ENTER USER ID
var photolist = [];
$.getJSON('https://www.flickr.com/services/rest/?method=flickr.people.getPhotos&api_key=' + API_KEY + '&user_id=' + USER_ID + '&format=json&jsoncallback=?', function(rest) {
var numPhotos = rest.photos.pages;
for (var u =0; u < numPhotos; u++) {
$.getJSON('https://www.flickr.com/services/rest/?method=flickr.people.getPhotos&api_key=' + API_KEY + '&user_id=' + USER_ID + '&format=json&jsoncallback=?&pages=' + u, function(results) {
for (var m =0; m < results.photos.total; m++) {
photolist.push("https://www.flickr.com/" + results.photos.photo[m].owner + "/" + results.photos.photo[m].id);
}
});
}
});
});
</script>
</head>
<body>
<div id="fotolist">
</div>
</body>
</html>
Use .append if you want to push content into an already existing div. Make sure targetDiv is declared outside the $.getJSON call.
var targetDiv = $('#printDiv');
for (var m =0; m < results.photos.total; m++)
{
targetDiv.append("https://www.flickr.com/" +
results.photos.photo[m].owner + "/" + results.photos.photo[m].id);
}
Push items to an array
Join the items in the array
.append() the items to your target
DEMO
jQuery:
var myList = [];
for (var i = 0; i < 9; i++) {
myList.push('<li>');
myList.push('My name is Agent 00' + i);
myList.push('</li>');
}
$("#target").append(myList.join(''));
HTML:
<ul id="target"></ul>
This will do the trick.
a. Here is a one liner assuming array contains only links:
$("#fotolist").append(photolist.join(" </br> "));
</br> is present to break the lines, if you don't want to break line, just remove that part
b. Paste the code after the for loop.
$.each(photolist, function(){
$("#fotolist").append(this);
});
c. Though the above method will work, we are refreshing the DOM often.
So you need to create a DOM fragment and add all text/html to it and then append it to DOM for performance reasons.
var html = "";
$.each(photolist, function(){
html +=this;
});
$("#fotolist").append(html);
EXAMPLE

Categories

Resources