How can I add loop in after function? - javascript

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

Related

page doesn't display anything

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>`

How to add for loop inside jquery

i have array of data in mysql database, i want to display it one by one using for loop after getting the results using ajax. the process goes like this.
this is the paragraph where each items going to be rendered
when i try using for loop it says syntax error, unexpected for loop taken, how can i fix this
i.e. here i am using sample for loop in order to make things as easy as possible.
$("#manager_paymentA").html(
'<ul>'+
for(let i=0; i < 5; i++) {
'<li>Hello</li>'
}
+ '</ ul>'
)
You cannot loop inside the html function.
You should store the data into a variable:
var hello = ''
for(let i=0; i < 5; i++) {
hello += '<li>Hello</li>'
}
$("#manager_paymentA").html('<ul>'+ hello + '</ ul>')
You can use jQuery append method.
Example :
$("#manager_paymentA").append("<ul></ul>"); // Create the list
for(let i=0; i < 5; i++) {
$("#manager_paymentA > ul").append("<li>Hello</li>"); // Append elements
}
You can not put the for loop inside the html function and add it between strings.
First build the string in a string variable, and than use that variable in the html function. example:
var html = '<ul>';
for(let i=0; i < 5; i++) {
html += '<li>Hello</li>'
}
html += '</ ul>' ;
$("#manager_paymentA").html();
Just for the sake of proving that creating a string with a loop in-line CAN (somewhat) be done in Javascript:
$("#manager_paymentA").html(
'<ul>'+
(() => {
let s="";
for(let i=0; i < 5; i++) {
s += '<li>Hello</li>'
}
return s;
})()
+ '</ ul>'
)
While this works, it's not really something I would recommend doing.
//data is your array list
data.forEach(item=>
$('#manager_paymentA ul').append('<li>'+item.Name+'</li>');
)
You can access list items with the item element

Saving all variables using loop and localStorage [JavaScript]

I wanted to make a code that will easily save all variables. Normally i would need for 60 variables about 120 lines. Not very efficient. I decided to try to make one function with array to try to save all variables. It doesnt seem to work.
My problem is that loaded variables are string, but i need them to be float.
var variablelist = ["numb1","numb2","numb3","numb4","numb5"];
var variablelength = variablelist.length;
function save(){
for (var i = 0; i < variablelength; i++){
localStorage[variablelist[i]] = window[variablelist[i]];
}
}
function load(){
for (var i = 0; i < variablelength; i++){
window[variablelist[i]] = localStorage[variablelist[i]];
}
}
I have tried
window[variablelist[i]] = localStorage[parseFloat(variablelist[i])];
Nothing has worked. It is still a string. Any ideas ?
First of all, it hurts me to see so much stuff stored on the window object like that. You should really give that a re-think!
LocalStorage is a way of storing a key-value pair to the browsers memory for access later. The only catch is that the value has to be a string.
You can get around this my using the JSON.stringify and JSON.parse function:
var objectToSave = {
key1: 'something',
key2: 'something else'
};
localStorage.setItem('myObject', JSON.stringify(objectToSave));
console.log(localStorage.getItem('myObject')); // What is stored
console.log(JSON.parse(localStorage.getItem('myObject'))); // The parsed object
Otherwise, if you are set on saving all of the individual variables, you are not far off, you just need to use the getItem and setItem:
var variablelist = ["numb1","numb2","numb3","numb4","numb5"];
var variablelength = variablelist.length;
function save(){
for (var i = 0; i < variablelength; i++){
localStorage.setItem(variablelist[i], window[variablelist[i]]);
}
}
function load(){
for (var i = 0; i < variablelength; i++){
window[variablelist[i]] = localStorage.getItem(variablelist[i]);
}
}
Use localStore.setItem() and localStore.getItem() to store and load items. Also use JSON.stringify() and JSON.parse() to convert objects to text, and then restore them back to objects.
var variablelist = ["numb1","numb2","numb3","numb4","numb5"];
var variablelength = variablelist.length;
function save(){
for (var i = 0; i < variablelength; i++){
localStorage.setItem(variablelist[i], JSON.stringify(window[variablelist[i]]));
}
}
function load(){
for (var i = 0; i < variablelength; i++){
window[variablelist[i]] = JSON.parse(localStorage.getItem(variablelist[i]));
}
}

innerHTML write in a div

<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>

extract elements from two arrays with same value

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.

Categories