Looping inside a string in JavaScript - 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.

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>

Why doesn't my for loop execute?

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>

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;

Generate multiple div in jquery loop

I need to ask for help.
Having this code:
$(".apprezzamenti").click(function()
{
var id = $(this).attr('id');
$.get("http://localhost/laravel/public/index.php/apprezzamenti_modal/"+id,
function(data)
{
data_parsed = JSON.parse(data);
// BELOW is the loop that I would like to generate multiple div using .append()
for(var i=0; i<data_parsed.length; i++)
{
var html = '<img src="images/provvisorie/immagine-profilo.png" width="30px" and height="30x" />';
html += ' ';
html += "<a href='http://localhost/laravel/public/index.php/utente/" + data_parsed[i].id_user + "' style='font-weight: bold;'>" + data_parsed[i].username + "</a>";
$(".modal-body-apprezzamenti>p").append(html).append('.modal-body-apprezzamenti>p').append($('<br/>'));
}
$(".chiudi-popup").click(function()
{
$(".modal-body-apprezzamenti>p").html('');
});
$('#main').click(function()
{
$(".modal-body-apprezzamenti>p").html('');
});
});
});
I'd like to create a div for each looping.
How could I do? Thanks for your help.
With jQuery it's very easy, look at this JSFiddle
http://jsfiddle.net/Ldh9beLn/
I use the function jQuery appendTo() to insert each div inside another div with id = "inserts" if you don't understand a section of this code or how to adapt to yours leave me a comment.
var things = ["apple", "house", "cloud"];
for (var i = 0; i < things.length; i++) {
$("<div>"+things[i]+"</div>").appendTo("#inserts");
}

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