increasing a variable name by 1, on each loop - javascript

Using JS Adding a table with 'rowNumber', everytime code goes round the loop, increase value by 1 and create a new variable 'Row_Num' + value of rowNumber, to keep it unique.
var rowNumber = 1;
for (var attributeIndex in table.attributes) {
var Row_Num + rowNumber = table.insertRow(rowNumber);
rowNumber += 1;
//this isnt working, how can I get the value of rowNumber and add it onto the end of the variable each time?

As Frédéric pointed out, when you want to store lots of variables together, the best way to do this is with an Array.
So you can change your code a little bit like this so that all your row objects are stored in the array tableRows:
var rowNumber = 0; // arrays start with index 0, not 1.
var tableRows = new Array(); // store the rows in here
for (var attributeIndex in table.attributes) {
tableRows[rowNumber] = table.insertRow(rowNumber);
rowNumber += 1;
}
Then when you want to get hold of a particular value, you just need to access it using the index.
// get the 2nd entry - at index 1
var someRow = tableRows[1];

Related

Javascript code saving data to 2d array throws undefined

I'm writing a script that takes values from a html table, indexes them in aray and then assign every value to a tag in a form.Codepen https://codepen.io/anon/pen/eVLKyB
My problem is that after taking all specified values from array I get
Code responsible for indexing values from table look like this:
function size_index(){
var table = document.getElementsByClassName("product_table_cus");
var index= [[],[]];
var i_index = 0;
var iter = 0; //index of first dim of array
var len = table[0].rows.length;
console.log("Len:"+len);
while(i_index<len) {
//iterate trough rows
console.log("second for, iter:"+ i_index);
var col_inner = table[0].rows[i_index].cells[0].innerHTML; //size param
var col_param = table[0].rows[i_index].cells[1].innerHTML;//size value
var col_size = col_inner.substr(col_inner.indexOf(' ')+1);
console.log("Rozmiar:"+ col_size+" Wartość:"+col_param);
// index[1][0].push("col_size");
// index[i_index][1].push(col_param);
if(col_inner.search("Rozmiar")!==-1)
{
console.log("Inner wtf:"+col_inner+"Ite:"+iter);
index[iter].push(col_inner,col_param);
console.log("Index+:"+index[iter]);
console.log("Ind:"+col_inner+"Val:"+col_param);
}
else if(col_inner.search("Rozmiar")==-1){
}
iter++;
// col_param=0;
// col_size=0;
//iterate through columns
//columns would be accessed using the "col" variable assigned in the for loop
//rows would be accessed using the "row" variable assigned in the for loop
i_index++;
}
return index;
}
You can see it in the console log:
This line of code
console.log("Inner wtf:"+col_inner+"Ite:"+iter);
Produces this output
Inner wtf:Rozmiar XXLIte:2
Your index variable has exactly two values in it.
So of course, if iter is a value greater than one, this line will cause an error:
index[iter].push(col_inner,col_param);
There are two elements in index, so index[2] will return undefined.
Your underlying problem is that [[][]] is not a two dimensional array. It is an array containing two arrays.
A safer way to do this is:
var index= [];
Then, to add an element:
index[iter] = index[iter] || [];
index[iter].push(...);

How to randomly select numbers within an arbitrary range and add together using JavaScript arrays

I am trying to write some JavaScript that will select some random numbers from an array and then add those selected numbers to make a single total value.
For example if i had var array = [1, 22, 5, 88, 3, 105, 7, 88, 987] i would then like the code to select however many numbers it wants at random(amount selected changes every time it runs) and then add them together but i am not sure if this is even possible.
I am new to JavaScript so i have only managed to write code that adds all the array elements together instead of selecting at random.
var arr = [1,2,3,4,5,6];
var total=0;
for(var i in arr) { total += arr[i]; }
My code is very basic so please excuse me for this i'm still learning. Thank You
You could use the Math.rand() function in order to create a random index. In terms of code:
// The array with your elements
var arr = [1,2,3,4,5,6];
// An array that will keep track of the elements we have selected.
var selectedIndex = [];
// The sum.
var sum=0;
// times is the number of elements we want to select from arr and sum them.
for(var i=0; i<times; i++)
{
// Get a random integer number in the range [0, arr.length]
var index = Math.floor(Math.rand()*arr.length);
// check if the index we created has been selected again.
if(selectedIndex.indexOf(index)>-1)
{
// The created index has been selected again. So we must select another one,
// in order we get an item from the array only once.
while(selectedIndex.indexOf(index)>-1)
index = Math.floor(Math.rand()*arr.length);
}
// We push the created index in the selected index array.
selectedIndex.push(index);
// We increase the sum.
sum+=arr[index];
}
update
In order the above to be executed the caller should provide a value for the variable called times. This value in order to be valid shouldn't exceed the length of the array called arr.
Another way more elegant, it would be to follow on this part the solution that deitch suggested in his post.
var times = Math.floor((Math.random() * arr.length)+1)
The above should be placed just before the for statement.
I think you are looking something like:
<code>
function randormTotal() {
var arr = [1,2,3,4,5,6];
var total=0;
var noOfData = 3;
for(var i =0; i<noOfData; i++) {
var pos = Math.floor(Math.random()*(arr.length-1)) + 1;
total += arr[pos];
}
alert(total);
}
</code>
FYI, this method actually modifies the array, so you might want to copy it.
// randomly select how many elements you will pick
var i, total = 0, elmsCount = Math.floor((Math.random() * arr.length)+1), current;
// select that many elements
for (i=0; i<elmsCount; i++) {
current = Math.floor(Math.random()*arr.length);
total += arr.splice(current,1)[0];
}
// total is now the sum

Adding for loop results to an array and displaying sum of added elements after the last loop

I have to get some records based on weekly basis for the last weeks, and have to add values from records of one week to an array. So, I declared 6 arrays to store 6 weeks records. My code is:
var w_0 = [];var w_1 = [];var w_2 = [];var w_3 = [];var w_4 = [];var w_5 = [];
var myTotal = 0;
var arr_name = "";
for(var j=0;j<=5;j++)
{
var start_date="";
var end_date="";
//code to fetch the records added between start_date,end_date
//there may be more that one record
var count = getRecordCount(); //My function
//following loop is to fetch value from a record
for(var i=0;i<count;i++)
{
var val1 = getRecordByIndex(i).getValue("rem_val"); //getRecordByIndex() and getValue() are our pre-defined functions.
//here I want to push the values into the array w_0
arr_name = "w_"+j;
[arr_name].push(val1); //this is not working
alert([arr_name]); //showing 'w_0'
}
//and here I want to sum all the array elements when i reaches its maximum
for(var a=0;a<[arr_name].length; a++){
myTotal += parseInt([arr_name][a]);
}
alert("Total value of week"+j+"="+parseInt(myTotal));
}
How can I add values of inner loop to the array based on outer loop?
Any time you find yourself creating variables with sequentially numbered names, you should probably be using an array instead.
var w = [[], [], [], [], []];
Then, wherever you tried to use [arr_name] to refer to a particular w_j variable, you should use w[j].
for(var j=0;j<=w.length;j++)
{
var cur_w = w[j];
var start_date="";
var end_date="";
//code to fetch the records added between start_date,end_date
//there may be more that one record
var count = getRecordCount(); //My function
//following loop is to fetch value from a record
for(var i=0;i<count;i++)
{
var val1 = getRecordByIndex(i).getValue("rem_val"); //getRecordByIndex() and getValue() are our pre-defined functions.
cur_w.push(val1);
alert(cur_w);
}
//and here I want to sum all the array elements when i reaches its maximum
for(var a=0;a<cur_w.length; a++){
myTotal += parseInt(cur_w[a]);
}
alert("Total value of week"+j+"="+parseInt(myTotal));
}
If you want to dynamically manipulate global variables you can use window prefix:
arr_name = "w_"+j;
window[arr_name].push(val1); // This should work

Find Index of Column(s) after it has been Moved

We are using DHTMLX Grid. Need some help, please.
I have a table and each columns (has filter/dropdown) are allocated an id eg. fac, date, sel, loc, tag ... etc
We have hard coded the index of columns to set and get the cookie elsewhere.
function doInitGrid(){
mygrid.setColumnIds("fac,date,sel,loc,tag"); //set ids
mygrid.attachEvent("onFilterStart",function(ind,data)
{
setCookie("Tray_fac_filter",mygrid.getFilterElement(0).value,365); //column index 0
setCookie("Tray_loc_filter",mygrid.getFilterElement(3).value,365);//column index 3
setCookie("Tray_tag_filter",mygrid.getFilterElement(4).value,365); //column index 4
mygrid.getFilterElement(0).value = getCookie("Tray_fac_filter")
mygrid.getFilterElement(3).value = getCookie("Tray_dep_filter")
mygrid.getFilterElement(4).value = getCookie("Tray_prg_filter")
});
}
But when the columns are moved, the problem arises as the index of the column changes yet it is set in setCookie /getCoookie
DHTMLX allows to get the index of the id using --
var colInd = grid.getColIndexById(id);
eg: var colInd = grid.getColIndexById(date); // outputs 1.
After moving the date column to the end -- fac, sel, loc, tag, date // it will output 4.
However, we have about 14 columns that can be moved/rearranged and I could use the
var colInd = grid.getColIndexById(id); 15 times
var facInd = grid.getColIndexById("fac");
var dateInd = grid.getColIndexById("date");
var selInd = grid.getColIndexById("sel");
var locInd = grid.getColIndexById("loc";
var tagInd = grid.getColIndexById("tag");
and put those variables in the set/get cookie. I was thinking if there was a better way.
To understand the code better, I have put the minimised version of the code in fiddle.
http://jsfiddle.net/19eggs/s5myW/2/
You've got the best answer I think. Do it in a loop and it's easier:
var cookie_prefix = "Fray_filter_";
var cookie_dur = 365;
var num_cols = dhx_grid.getColumnCount();
// filter vals to cookies
for (var col_idx=0; col_idx<num_cols; col_idx++) {
var filter = mygrid.getFilterElement(col_idx)
if (filter) { // not all columns may have a filter
var col_id = dhx_grid.getColumnId(col_idx);
var cookie_name = cookie_prefix+col_id;
setCookie(cookie_name, filter.value, cookie_dur);
}
}
// cookies to filter vals
for (var col_idx=0; col_idx<num_cols; col_idx++) {
var col_id = dhx_grid.getColumnId(col_idx);
var filter_val = getCookie(cookie_prefix+col_id);
var filter = mygrid.getFilterElement(col_idx)
filter.value = filter_val;
}
You can use dhtmlxgrid native event to assign the correct id everytime a column is moved.
The event is called onAfterCMove, you can check the documentation here. onAfterCMove Event
You would do something like:
mygrid.attachEvent('onAfterCMove',function(cInd,posInd){
//Your processing here to change the cookies; where cInd is the index of the column moved
//and posInd, is the position where it Was moved
}):

How make jquery loop over with number

I am trying to assign a number to my variable i.e. colorswap1, colorswap 2, colorswap 3
I have the following
var i = 1-36;
// Get current image src
var curSrc = $('#colorswap'[i]).attr('src');
It doesn't seem to be putting the desired: colorswap1, colorswap2
Your variable declaration is doing the algebraic subtraction and will result in -35. You need a loop of some sort. Then, you concatenate the index with the string using the + operator. Because one of the things is a string, it will concatenate instead of "add".
Below is an example of what you can do:
for (var i = 1; i <= 36; i++) {
var curSrc = $('#colorswap' + i).attr('src');
// now do stuff with curSrc here
}

Categories

Resources