<div id="story"></div>
<script>
function go(){
var test = [];
for (i=1; i<11; i++){
test[i]=i;
var words = document.getElementById(test[i]).value
document.getElementById("story").innerHTML="hello "+test[i];
}
}
I want everything from the for loop to be written in the div. However, only the last value of the loop (10) is being written into the div. How can i get all of the values written in there?
you are replacing the innerHTML you want to concatenate use +=
document.getElementById("story").innerHTML+="hello "+test[i];
or
document.getElementById("story").innerHTML =
document.getElementById("story").innerHTML + "hello "+test[i];
All the values are written to the element, but each value overwrites the previous one.
Collect the values in an array, and write them all to the element after the loop. Example:
<div id="story"></div>
<script>
function go(){
var test = [];
var msg = [];
for (i=1; i<11; i++){
test[i]=i;
var words = document.getElementById(test[i]).value
msg.push("hello "+test[i]);
}
document.getElementById("story").innerHTML = msg.join(', ');
}
go();
</script>
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>`
My javascript is like this :
$('#thumbnail-view').after(` for(i=0;i<5;i++){ <div>....</div }`);
I want to add loop in after like that
How can I do it?
You can build the string first, before calling the after() function.
For example, this appends the string 123456789 using a loop.
var res = "";
for (var i = 1; i <= 9; i++) {
res += i;
}
$('#thumbnail-view').after(res);
This how you can achieve what you need exactly.
$('#thumbnail-view').after((function(){
// Here you can write you for loop and return the concatenated string
var str = "";
for(var i=0; i< 10; i++) {
str = str + "<div>test</div>";
}
return str;
})());
});
It basically creates an IFFE. which executes immediately and returns a string for '$.after()' to consume.
What you really need is to create a variable that has all the elements you want. then pass that variable to the after. Do not create a function inside of after. There is no need for it.
$(document).ready(function(){
var divvs = '';
for(var i=0;i<5;i++){
divvs+= '<div>hello</div>'
}
$('.block').after(divvs);
});
Here is the fiddle for reference http://jsbin.com/biluqanupo/edit?html,js,output
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>
Hello I want to extract elements from both arrays with the same url .How can i loop these two arrays and get their content, because it gives me undefined for the news_url and i think it outputs twice the items in the console.
function geo(news_array,user_tweets){
console.log(news_array,user_tweets);
for (var x=0; x<user_tweets.length; x++) {
var user = user_tweets[x].user;
var date = user_tweets[x].date;
var profile_img = user_tweets[x].profile_img;
var text = user_tweets[x].text;
var url=user_tweets[x].url;
second(user,date,profile_img,text,url);
}
function second(user,date,profile_img,text,url){
for (var i = 0; i < news_array.length; i++) {
var news_user = news_array[i].news_user;
var news_date = news_array[i].news_date;
var news_profile_img = news_array[i].news_profile_img;
var news_text = news_array[i].news_text;
var news_url=news_array[i].url;
if (url==news_array[i].news_url) {
geocode(user,date,profile_img,text,url,news_user,news_date,news_profile_img,news_text,news_url);
}
}
}
function geocode(user,date,profile_img,text,url,news_user,news_date,news_profile_img,news_text,news_url) {
console.log(url,news_url);
}
}
The problem is
in news_tweets function, you add news_url to news_array. So you should call
news_array[i].news_url
in second function.
I modify your code as
news_url: (item.entities.urls.length > 0)?item.entities.urls[0].url : '' in news_tweets function
add close brace } for geo function and remove } from last
add new_array parameter to second function like second(user, date, profile_img, text, url,news_array);
Modify code can be tested in http://jsfiddle.net/rhjJb/7/
You have to declare some variables before the first for loop, so that they can be accessed in the scope of the second function. Try to replace your first for loop with the following code:
var user, date, profile_img, text, url;
for (var x=0; x<user_tweets.length; x++){
user = user_tweets[x].user;
date = user_tweets[x].date;
profile_img = user_tweets[x].profile_img;
text = user_tweets[x].text;
url=user_tweets[x].url;
second(user,date,profile_img,text,url);
}
Moreover, in the if of your second function, news_array[i].news_url isn't defined. Use if (url == news_url) instead.
First, how do you append data to the end of a variable in Javascript? I know for PHP you use:
$foo = "bar";
$foo.= "bar2";
Next, I can get the following to work for one form field:
var test = document.form1.option1.value;
However, how would I go about doing this with a for loop whilst appending each iteration onto the end of the variable? For example (where XXX is the loop variable i):
for(i=0; i<10; i++){
test.= document.form1.optionXXX.value;
}
Basically, I need all the data from a random set of form fields that can range anywhere from option1 to option20. Thanks.
Try using this notation to avoid eval().
for(i=0; i<10; i++){
test += document.form1['option' + i].value;
}
var test = "";
for (var i=0; i<10; i++){
test += document.form1["option" + i].value;
}