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;
}
Related
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
So I have this 2D array in JavaScript and trying to print its elements using innerHTML or document.write, but using innerHTML in a for loop overrides all elements on each other. using document.write puts all elements in a row (which I don't more than 3 elements in a row), so please help me find a way! (I know my solution is super wrong, but I'm just trying to show what I'm thinking of)
const myData = function(){
return
[[{"number":1,"name":"Jack","day":"Sat"},
{"number":2,"name":"Max","day":"Sun"}],
[{"number":3,"name":"Al","day":"Mon"},
{"number":4,"name":"Jacky","day":"Tues"}
{"number":5,"name":"Daniel","day":"Wed"}]];
};
var array = myData();
var len = array.length;
var i, j;
for (i=0; i<len; i++){
for (j=0; j<3; j++){
document.getElementByID(demo).innerHTML = array[i][j].number;
document.getElementByID(demo).innerHTML = array[i][j].day;
document.getElementByID(demo).innerHTML = array[i][j].name;
}
}
You can concatenate the innerHTML, so it will have the old value and the new one too.
just put a + before the =:
document.getElementByID(demo).innerHTML += array[i][j].number;
document.getElementByID(demo).innerHTML += array[i][j].day;
document.getElementByID(demo).innerHTML += array[i][j].name;
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 want to create a dynamic variable in the loop.
I found something about eval and window but I don't know how to use this.
This is my loop and i want to create a 9 variables names from m1 to m9. I mean that the name of variable must be m1 to m9
for(i=1; i<10; i++){
var m+i = "Something"
}
Please help me with this. Really appreciate.
You don't want to create 9 variables. Trust me. You want to create an object.
var m = {};
for(var i=1; i<10; i++){
m[i] = "Something";
}
You can also create an array (m = []), but since you are starting at 1 and not 0, I'd suggest an object.
But if you still want to create 9 variables, despite all that, you still can:
for(i=1; i<10; i++){
eval('var m'+i+'='+i)
}
(And yes, you shouldn't).
var object = {};
var name = "m";
for(i=1; i<10; i++){
object[name+i] = "Something";
}
console.log(object.m1); // "Something", same for m2,m3,m4,m5...,m9
However consider if the "m" is really necessary, arrays are way faster:
var array = [];
for(i=1; i<10; i++){
array.push("Something");
}
console.log(array[0]); // "Something", same for 1,2,...,8
The following is my JSON data in a div:
[{"Identifier":"1","Label":"10 Day","Categories":"Standard","UpdatedBy":"Lno","UpdatedAt":"01-02-2013","RefId":"0","ComType":"1","Cs":["944"],"AM":"Error Message","Message":"asdfasdf","Combiner":[{"uniqueID":"1","type":"7","rule":""}]}]
I am accessing it through a JS object:
var myArrayVar=JSON.parse(document.getElementById("populateDT").innerHTML);
I want to iterate over this JS object. The following is my code, but it doesn't access my key/value fields:
for(var i=0; i<=myArrayVar.length;i++){
for(var j=0; j<=myArrayVar.Combiner.length; j++){
var sessionUniqueId= myArrayVar.Combiner[j].uniqueID;
alert(sessionUniqueId);
var sessionType=myArrayVar.Combiner[j].type;
alert(sessionType);
var sessionRule=myArrayVar.Combiner[j].rule;
alert(sessionRule);
}
}
Can anyone suggest a solution?
for (var i = 0; i < myArrayVar.length; i++) {
for (var j = 0; j < myArrayVar[i].Combiner.length; j++) {
var sessionUniqueId = myArrayVar[i].Combiner[j].uniqueID;
alert(sessionUniqueId);
var sessionType = myArrayVar[i].Combiner[j].type;
alert(sessionType);
var sessionRule = myArrayVar[i].Combiner[j].rule;
alert(sessionRule);
}
}
You never use i. You need it to access the current array element, for example:
for(var j=0; j<=myArrayVar[i].Combiner.length; j++){
myArrayVar is your array, myArrayVar[i] is the i-th element in that array and myArrayVar[i].Combiner is the combiner (array) property of the i-th element.
You'll make it yourself a lot easier if you give the current element a name as well. (You probably want to come up with a less generic name such as current though.)
for(var i=0; i<myArrayVar.length;i++){
var current=myArrayVar[i];
for(var j=0; j<current.Combiner.length; j++){
var sessionUniqueId=current.Combiner[j].uniqueID;
alert(sessionUniqueId);
var sessionType=current.Combiner[j].type;
alert(sessionType);
var sessionRule=current.Combiner[j].rule;
alert(sessionRule);
}
}
Also, i cannot equal myArrayVar.length as that index is already out of bounds. Your loop condition should have < instead of <=.
You have an array with one element. That element is in myArrayVar[0] and it is an object. To iterate over the object use a for ... in loop.
var myObj = myArrayVar[0];
for(var key in myObj){
var value = myObj[key];
console.log(key, value);
}
You should also use console.log for debugging. It will show you more information about objects than alert can.
Try using "<" instead of "<=" in the for loops, and "myArrayVar[i].Combiner" instead of "myArrayVar.Combiner".
There are a couple of problems I see. First, your i and j variables go one spot too far. They should be using < instead of <=.
Secondly, you're declaring variables inside the loop. That's fine, but JavaScript isn't block scoped, so you really end up with the same three variables overwriting each other as many times as there are items in the list. Your example data only has one item so you probably won't notice the overwriting problem just yet–but once you have multiple items in the list it could be a problem.