Making a variable name a dynamic variable - javascript

I hope someone can help me with the following...
I have this code below it is written in classic asp and javascript...
I have this variable in the code below my2String1 how can I make this a dynamic variable like:
my2String1_1
my2String1_2
my2String1_3
I have a database value Recordset2.Fields.Item("article_no").Value which could be the dynamic value like:
my2String1_Recordset2.Fields.Item("article_no").Value (which should do the trick) but I am not sure how to implement it...
while((Repeat1__numRows-- != 0) && (!Recordset2.EOF)) {
var my2String1 = ""+(Recordset2.Fields.Item("article_description").Value)+"";
my2String = my2String1;
var my2regexp = new RegExp(checkduplicates, "ig");
my2Array = my2String1.match(my2regexp);
my2length = my2Array.length;
for (i = 0; i < my2length; i++) {
my2Array[i] = '\''+my2Array[i]+'\'';
}
var arr = (myArray+my2Array).split(',');
var sorted_arr = arr.sort();
var results = [];
for (var i = 0; i < arr.length - 1; i += 1) {
if (sorted_arr[i + 1] == sorted_arr[i]) {
results.push(sorted_arr[i]);
}
}
Repeat1__index++;
Recordset2.MoveNext();
}
If you have any ideas on how to solve this please help me

I'm going to ignore that load of code because it clouding the issue. The feature of JScript you are looking to for is the ability to create named properties on an object:-
var myDescriptions = {}
var name = "Test"
var description = "This is a test"
myDescriptions[name] = description;
Response.Write(myDescriptions[name]);
Would send "This is a test" to the response.

Related

JavaScript Array & Global Variable Reference

I am trying to reference a global variable's value using my array output but I am unsure how to do that. I want to make these references outside the function as I will need to create many functions that use these variables.
Ignore the PFGetValue part, I need to use that for the program I am coding in. There will be many more dd_meg_x but this is just to show you what I'm doing. Currently, this will return the correct the text "dd_meg_x" - but I want to then reference the variable defined above. So for example, if the result in the array is dd_meg_1, I want the output to be "M Energy 16"
var dd_meg_1 = "M Energy 16";
var dd_meg_2 = "Ulra Energy";
var dd_meg_3 = "Another Option Here";
function canOrderMeg1() {
var brand = "meg";
var arrayLength = 21;
var canArray = [];
var variableName;
for (i = 0; i <= arrayLength; i++) {
variableName = ("dd_" + brand + "_" + i);
if (PFGetValue(variableName) === "Y") {
canArray.push(variableName);
}
canArray.join(", ");
}
return canArray[0];
}
function canOrderMeg2() {
var brand = "meg";
var arrayLength = 21;
var canArray = [];
var variableName;
for (i = 0; i <= arrayLength; i++) {
variableName = ("dd_" + brand + "_" + i);
if (PFGetValue(variableName) === "Y") {
canArray.push(variableName);
}
canArray.join(", ");
}
return canArray[1];
}
Try
return eval('string output code');
So this would look like
return eval(array output);
Try this:
var dd_meg_1 = "M Energy 16";
var dd_meg_2 = "Ulra Energy";
var dd_meg_3 = "Another Option Here";
function canOrderMeg1() {
return ["dd_meg_1", "dd_meg_2", "dd_meg_3"];
}
for(let i = 0; i < canOrderMeg1().length; i++){
if(typeof canOrderMeg1()[i] !== "undefined") {
console.log(window[canOrderMeg1()[i]]);
}
}

JavaScript Fires too fast. Objects not loaded

I have the below JavaScript running on one of my forms OnLoad event :-
function calcServicePriceTotal() {
var grid = document.getElementById('ProjectServicesGrid');
var ids = grid.control.get_allRecordIds();
var sum = 0.00;
var cellValue;
for (i = 0; i < ids.length; i++) {
var cellValue = grid.control.getCellValue('iss_salesprice', ids[i]);
var number = Number(cellValue.replace(/[^0-9\.]+/g, ""));
sum = sum + number;
}
Xrm.Page.data.entity.attributes.get("ava_tempgrossvalue").setValue(sum);
}
Unfortunately I get the following error :-
"Error:'subGridOnload' is undefined"
I believe that the script is firing before the object has had the time it needs to load so what can I do to slow down the function? There must be some way to overcome this but I am far from a JavaScript expert so I could use some help.
Thanks in advance
function calcServicePriceTotal() {
if (document.getElementById("Services")) {
var grid = document.getElementById("Services").control;
var ids = grid.get_allRecordIds()
var sum = 0
for (i = 0; i < ids.length; i++) {
var cellValue = grid.getCellValue('iss_salesprice', ids[i]);
var number = Number(cellValue.replace(/\D/g, ''));
number = number/100;
sum = sum + number;
}
Xrm.Page.data.entity.attributes.get("iss_value").setValue(sum);
}
else {
setTimeout("calcServicePriceTotal();", 500);
}
}

Adding a running sum to a javascript object

I have a javascript object as below
var mydata=[
{"Club":"Blackburn","EventNo":1,"Pnts":3,"CumPnts":0},
{"Club":"Blackburn","EventNo":2,"Pnts":1,"CumPnts":0},
{"Club":"Blackburn","EventNo":3,"Pnts":4,"CumPnts":0},
{"Club":"Preston","EventNo":1,"Pnts":2,"CumPnts":0},
{"Club":"Preston","EventNo":2,"Pnts":4,"CumPnts":0},
{"Club":"Preston","EventNo":3,"Pnts":2,"CumPnts":0},]
I want to update the object so that CumPnts contains a running points total for each Club as below
{"Club":"Blackburn","EventNo":1,"Pnts":3,"CumPnts":3},
{"Club":"Blackburn","EventNo":2,"Pnts":1,"CumPnts":4},
{"Club":"Blackburn","EventNo":3,"Pnts":4,"CumPnts":8},
{"Club":"Preston","EventNo":1,"Pnts":2,"CumPnts":2},
{"Club":"Preston","EventNo":2,"Pnts":4,"CumPnts":6},
{"Club":"Preston","EventNo":3,"Pnts":1,"CumPnts":7},]
Any help would be much appreciated
Here is a function that loops through the list and updates it after it's been added. But I suspect that the events come in one at a time so there could be another function that can look the cumPtns obj and take from that. Here is for the current list.
var cumData = {};
var mydata=[
{"Club":"Blackburn","EventNo":1,"Pnts":3,"CumPnts":0},
{"Club":"Blackburn","EventNo":2,"Pnts":1,"CumPnts":0},
{"Club":"Blackburn","EventNo":3,"Pnts":4,"CumPnts":0},
{"Club":"Preston","EventNo":1,"Pnts":2,"CumPnts":0},
{"Club":"Preston","EventNo":2,"Pnts":4,"CumPnts":0},
{"Club":"Preston","EventNo":3,"Pnts":2,"CumPnts":0}];
function updateMyData() {
for (var i = 0; i < mydata.length; i++) {
var item = mydata[i];
if(cumData[item.Club] == undefined) {
cumData[item.Club] = {};
cumData[item.Club] = item.Pnts;
} else {
cumData[item.Club] = cumData[item.Club] + item.Pnts;
}
mydata[i].CumPnts = cumData[item.Club];
};
console.log(mydata);
//if you want to return it you can have this line below. Otherwise the object is updated so you'll probably want to do something with it once it's updated. Call back maybe?
return mydata;
}
updateMyData();
The first time it encounters a team it adds it to an array and so does with the corresponding cumPnts, so we can keep track of whether we checked a team earlier or not.
var tmArr = [];
var cumArr = [];
for(var i = 0; i < mydata.length; i++) {
var elm = mydata[i];
var club = elm.Club;
var points = elm.Pnts;
var idx = tmArr.indexOf(club);
if(idx > -1) {
cumArr[idx] += points;
elm.CumPnts = cumArr[idx];
}
else {
elm.CumPnts = points;
tmArr[tmArr.length] = club;
cumArr[cumArr.length] = points;
}
}
jsfiddle DEMO

Scroll text method, works with arrays, not with string

Basic javascript function to scroll the text in the title bar, I'm calling it via a setInterval("rotateTitle()", 1000); call after onload.
This function, which takes text from an array, works perfectly.
var counter = 0;
function rotateTitle() {
var baseTitle = "www.mydomain.com - now with JavaScript";
var titleArray = new Array("a","b","c","d","e","f","g");
var titleString = "abcdefg";
var scrollText = getNextScroll(titleArray);
window.document.title=baseTitle.concat(scrollText);
}
function getNextScroll(inValue) {
var str = " ";
for (var i = 0; i<inValue.length; i++) {
var index = i+counter;
if (i+counter >= inValue.length) {
index -= inValue.length;
}
str += inValue[index];
}
counter++;
if (counter > inValue.length) {
counter = 0;
}
return str;
}
Edited here for clarity:
Now if I rewrite the function to scroll a string (not an array), I change the line
str += inValue[index];
to
str.concat(inValue.charAt(index));
and change getNextScroll(titleArray) to getNextScroll(titleString), the script seems to execute, but only the baseTitle is shown.
Why is this wrong?
You have to assign the result of str.concat back to str; otherwise you'll miss the concat operation. Instead of charAt you must use inValue[index].
Do like this:
str = str.concat(inValue[index]);
Here's a JS Bin: http://jsbin.com/aCEBAju/2/
In your original code you have this:
str.concat(inValue.charAt(index));
debugging in Chrome it barks: array has no method charAt.
The solution to the problem is that str.concat(inValue.charAt(index)); must change to str = str.concat(inValue.charAt(index)); or str += inValue.charAt(index);. Str must be assigned the new value. This is the entire working function:
var counter = 0;
function rotateTitle() {
var baseTitle = "www.berrmal.com - now with JavaScript";
var titleArray = new Array("b","e","r","r","m","a","l"); //no longer necessary
var titleString = "berrmal: bigger, longer, uncut";
var scrollText = getNextScroll(titleString);
window.document.title=baseTitle.concat(scrollText);
}
function getNextScroll(inString) {
var str = " ";
for (var i = 0; i<inString.length; i++) {
var index = i+counter;
if (i+counter >= inString.length) {
index -= inString.length;
}
str += inString.charAt(index);
}
counter++;
if (counter > inString.length) {
counter = 0;
}
return str;
}
I figured out the answer to the problem based on Leniel Macaferi's answer, though his posted code is not correct. This method runs successfully in Firefox 23.0 with no error in the console.

Google Apps Script: How to find a listItem object in a google document and insert a item to it?

Following the documentation sample, I'm trying to create a function that searchs for a numerated list in a google document and, if finds it, adds a new item to that list. But I get this error: Cannot find method setListId(string). (line 21, file "test") or, if I change line 21 content (replacing elementContentfor newElement), I get the message: Preparing for execution... and nothing happens. How to fix it?
This is my code:
function test() {
var elementContent = "New item testing"; // a paragraph with its formating
var targetDocId = "1R2c3vo9oOOjjlDR_n5L6Tf9yb-luzt4IxpHwwZoTeLE";
var targetDoc = DocumentApp.openById(targetDocId);
var body = targetDoc.getBody();
for (var i = 0; i < targetDoc.getNumChildren(); i++) {
var child = targetDoc.getChild(i);
if (child.getType() == DocumentApp.ElementType.LIST_ITEM){
var listId = child.getListId();
var newElement = body.appendListItem(elementContent);
newElement.setListId(newElement);
Logger.log("child = " + child);
}
}
}
Following my comment, I tried to play with your script to see what happened and I came up with that code below...
I'm not saying it solves your issue and/or is the best way to achieve what you want but at least it gives a result that works as expected.
Please consider it as a "new playground" and keep experimenting on it to make it better ;-)
function test() {
var elementContent = "New item testing"; // a paragraph with its formating
var targetDocId = DocumentApp.getActiveDocument().getId();
var targetDoc = DocumentApp.openById(targetDocId);
var body = targetDoc.getBody();
var childIndex = 0;
for (var i = 0; i < targetDoc.getNumChildren(); i++) {
var child = targetDoc.getChild(i);
if (child.getType() == DocumentApp.ElementType.LIST_ITEM){
while(child.getType() == DocumentApp.ElementType.LIST_ITEM){
child = targetDoc.getChild(i)
childIndex = body.getChildIndex(child);
Logger.log(childIndex)
i++
}
child = targetDoc.getChild(i-2)
var listId = child.getListId();
Logger.log(childIndex)
var newElement = child.getParent().insertListItem(childIndex, elementContent);
newElement.setListId(child);
break;
}
}
}

Categories