How to change array variable name dynamically - javascript

I am working for some common method in javascript, for that i have to call array dynamically.
var ddlText, ddlValue, ddl, lblMesg, ddlTextCacheList_Designation, ddlValueCacheList_Designation, ddlTextCacheList_Scale, ddlValueCacheList_Scale;
function cacheDes() {
var listDes = document.getElementById("<%=List_Designation.ClientID %>");
ddlTextCacheList_Designation = new Array();
ddlValueCacheList_Designation = new Array();
for (var i = 0; i < listDes.options.length; i++) {
ddlTextCacheList_Designation[ddlTextCacheList_Designation.length] = listDes.options[i].text;
ddlValueCacheList_Designation[ddlValueCacheList_Designation.length] = listDes.options[i].value;
}
}
function cacheScale() {
var listScale = document.getElementById("<%=List_Scale.ClientID %>");
ddlTextCacheList_Scale = new Array();
ddlValueCacheList_Scale = new Array();
for (var i = 0; i < listScale.options.length; i++) {
ddlTextCacheList_Scale[ddlTextCacheList_Scale.length] = listScale.options[i].text;
ddlValueCacheList_Scale[ddlValueCacheList_Scale.length] = listScale.options[i].value;
}
}
window.onload = function () {
cacheDes();
cacheScale();
};
I want to call array ddlTextCacheList_Scale or ddlTextCacheList_Designation for same method as we know 'ddlTextCacheList_' is common only we need to put 'Scale' or 'Designation' dynamicaaly by passing parameter.
Add:
I get some errors:

I suggest you to improve your cache to store all in one object to easy access...
For example:
var CacheStorage = {};
function cache(key, list) {
CacheStorage[key] = list.map(function(option){
return {text: option.text, value: option.value};
});
}
function del(key, index) {
CacheStorage[key].splice(index, 1);
}
cache('Scale', getElementByID('...').options);
cache('Designation', getElementByID('...').options);
del('Designation', 0);

Related

Concat in a for loop google app scripts javascript

I'm trying to filter in an array by data in another array using concat in a for loop. The elements of the following code are logging correctly, but the final array is logging an empty array.
function Shipments (){
var app = SpreadsheetApp;
var movementSS = app.getActiveSpreadsheet();
var infoSheet = movementSS.getSheetByName("Update Info");
var orderInfoSheet = movementSS.getSheetByName("Order Info");
var targetSheet = movementSS.getSheetByName("Shipments");
var ShipLogSS = app.openByUrl(URL).getSheetByName("Shipping Details");
var ShipArr = ShipLogSS.getRange(3,1,ShipLogSS.getLastRow(),ShipLogSS.getLastColumn()).getValues().
filter(function(item){if(item[1]!=""){return true}}).
map(function(r){return [r[0],r[1],r[2],r[4],r[10],r[11],r[16],r[18],r[23]]});
var supplierData = orderInfoSheet.getRange(3,6,orderInfoSheet.getLastRow(),1).getValues().
filter(function(item){if(item[0]!=""){return true}});
var supplierList = [];
for (var i in supplierData) {
var row = supplierData[i];
var duplicate = false;
for (var j in supplierList) {
if (row.join() == supplierList[j].join()) {
duplicate = true;
}
}
if (!duplicate) {
supplierList.push(row);
}
}
var supplierFilter = [];
for(var i = 0; i < supplierList.length; i++){
var shipments = ShipArr.filter(function(item){if(item[4]===supplierList[i][0]){return true}});
supplierFilter.concat(shipments);
}
Logger.log(supplierFilter);
}
Any help would be greatly appreciated!
You need to assign the result of concat onto the supplierFilter in order to see the changes in later iterations and in the outer scope.
You can also return the comparison done inside the .filter callback immediately, instead of an if statement - it looks a bit cleaner.
var supplierFilter = [];
for (var i = 0; i < supplierList.length; i++) {
var shipments = ShipArr.filter(function (item) { return item[4] === supplierList[i][0]; });
supplierFilter = supplierFilter.concat(shipments);
}
Logger.log(supplierFilter);

How to make a javascript function with elementid like argument?

I have an DevExpress Mvc token extension, where the user will insert several items.
Using javascript I send the items to the controller, which is working fine.
My function look like this:
$(function() {
$("#btnSave").click(function () {
var name = window.ComboBox.GetValue();
var i;
var team = new Array();
var tokens = window.tokenBox.GetTokenCollection();
for (i = 0; i < tokens.length; i++) {
team.push(tokens[i]);
}
var s = new Array();
var ss = window.tokenBox2.GetTokenCollection();
for (i = 0; i < ss.length; i++) {
s.push(ss[i]);
}
var w = new Array();
var ww = window.tokenBox3.GetTokenCollection();
for (i = 0; i < ww.length; i++) {
w.push(ww[i]);
}
var o = new Array();
var oo = window.tokenBox4.GetTokenCollection();
for (i = 0; i < oo.length; i++) {
o.push(oo[i]);
}
var t = new Array();
var tt = window.tokenBox5.GetTokenCollection();
for (i = 0; i < tt.length; i++) {
t.push(tt[i]);
}
$.ajax({
type: "post",
url: '#Url.Action("Action","Controller")',
data: { name:name, team:team, s:s, o:o, w:w, t:t },
beforeSend: function () {
window.loadingPanel.Show();
},
success: function (response) {
$("#mainAjax").html(response);
window.loadingPanel.Hide();
}
});
});
});
I want to use a function, to get the items from token and put them in an array (not repetitive code like above), something like this:
function GetTokenItems(token) {
var list = new Array();
var el = document.getElementsById(token);
var tokens = el.GetTokenCollection();
for (var i = 0; i < tokens.length; i++) {
list.push(tokens[i]);
}
return list;
};
This function is not working, error says:
Uncaught TypeError: document.getElementsById is not a function
How can I pass the Id of the tokenBok like argument in a function, or/and what is wrong with my function?
**Edit:**
I made the correction document.getElementById and now I get the error:
Uncaught TypeError: el.GetTokenCollection is not a function
Should be document.getElementById(id):
Returns a reference to the element by its ID; the ID is a string which can be used to identify the element; it can be established using the id attribute in HTML, or from script.
document.getElementById(...)
// ^ without s
I found the answer of my issue, maybe will be helpfull for others!
For Devexpress mvc extensions is enough to use the name of the extension like argument, no need to look for him with document.getElementById, so my function is working like this:
function GetTokenItems(token) {
var list = new Array();
var tokens = token.GetTokenCollection();
for (var i = 0; i < tokens.length; i++) {
list.push(tokens[i]);
}
return list;
};
now I can call this function like this:
var team=GetTokenItems(tokenBox); and is working!!!

JavaScript cannot find method a second time?

I'm attempting to build a poker game. The method in question is very simple, and it works when it runs the first time.
This part isn't perfect convention because I'm just using it to test my methods:
var $ = function (id) { return document.getElementById(id); };
var test = function() {
var deck = new POKER.Deck();
var hand = new POKER.Hand();
for (var i = 0; i < 7; i++){
hand.addCard(deck.dealCard());
}
hand.sortByRank();
for (var j = 0; j < 7; j++){
var img = document.createElement("img");
var card = hand.getCardAtIndex(j); //** <------- WORKS HERE**
img.src = card.getImage();
$("images").appendChild(img);
}
var testHand = new POKER.Hand();
testHand = hand.removePairs();
for (var k = 0; k < testHand.length; k++) {
var img2 = document.createElement("img");
var card2 = testHand.getCardAtIndex(k); // **<------FAILS HERE**
img2.src = card2.getImage();
$("handImg").appendChild(img2);
}
};
window.onload = function() {
test();
};
The first and second loop work, and the hand is displayed and everything. When it gets to the last loop, the debugger tells me "TypeError: testHand.getCardAtIndex is not a function"
I was attempting to test the removePairs method (to test for straights more easily), and when watching the variables in the debugger, testHand clearly gets populated correctly. The method seems to work just fine.
getCardAtIndex:
POKER.Hand.prototype.getCardAtIndex = function(index) {
return this.cards[index];
};
removePairs:
POKER.Hand.prototype.removePairs = function(){
var allCards = this.cards;
var tempCards = [];
var uniqueRanks = [];
var unique;
for(var i = 0; i < allCards.length; i++){
unique = true;
for(var j = 0; j < uniqueRanks.length; j++){
if(allCards[i].getRank() == uniqueRanks[j]){
unique = false;
break;
}
}
if(unique){
uniqueRanks.push(allCards[i].getRank());
tempCards.push(allCards[i]);
}
}
return tempCards;
};
I'm completely perplexed.
var testHand = new POKER.Hand();
testHand = hand.removePairs();
hand.removePairs() returns an Array, not a Hand object.
That's why you don't have access to the getCardAtIndex method.
If cards is a public property you could do:
testHand.cards = hand.removePairs();
Or you can have a setter method:
testHand.setCards(hand.removePairs);

Split values by comma separated string in javascript

Here is my issue:
I have RadListBox and I'm trying to get the values and append them so the result would be displayed like that: '1,2,3,4' but I'm getting back : 1,2,3,4,
Does anyone know how can I achieve that?
Problem starts here:
var sbLocationsIDS = new StringBuilder();
for (i = 0; i < LocationIDS.get_items().get_count(); i++) {
sbLocationsIDS.append(LocationIDS.getItem(i).get_value()+ ",");
}
The result: sbLocationsIDS =1,2,3,4, instead of '1,2,3,4'
The Rest of the Code:
function openNewTab(url) {
var captureURL = url;
var win = window.open(captureURL, '_blank');
win.focus();
}
function GetComparisonsReport(sender, args) {
var isValid = Page_ClientValidate('validateComparisons');
if (isValid) { // If its true is going to fire the rest of the code
var SessionID = getUrlVars()["SessionID"];
var companyCodeVal = document.getElementById("<%=hfC.ClientID%>").value;
var LocationIDS = $find("<%=rlbSelectedLocation.ClientID %>");
var CategoriesIDS = $find("<%=rlbSelectedCategory.ClientID %>");
var fileType = $find("<%=rcbFileType.ClientID %>");
var fromFirstPeriod = $find("<%=rdpFromFirstPeriod.ClientID %>");
var toFirstPeriod = $find("<%=rdpToFirstPeriod.ClientID %>");
var fromSecondPeriod = $find("<%=rdpFromSecondPeriod.ClientID %>");
var toSecondPeriod = $find("<%=rdpToSecondPeriod.ClientID %>");;
if (LocationIDS.get_items().get_count() < 0) {
radalert("Please choose locations and select the Add button.<h3 style='color: #ff0000;'></h3>", 420, 170, "Case Global Alert");
return;
}
if (CategoriesIDS.get_items().get_count() < 0) {
radalert("Please choose categories and select the Add button.<h3 style='color: #ff0000;'></h3>", 420, 170, "Case Global Alert");
return;
}
var fromFirstPeriodDateValSelected = fromFirstPeriod.get_dateInput().get_selectedDate().format("yyyy/MM/dd");
var toFirstPeriodDateValSelected = toFirstPeriod.get_dateInput().get_selectedDate().format("yyyy/MM/dd");
var fromSecondPeriodDateValSelected = fromSecondPeriod.get_dateInput().get_selectedDate().format("yyyy/MM/dd");
var toSecondPeriodDateValSelected = toSecondPeriod.get_dateInput().get_selectedDate().format("yyyy/MM/dd");
var fileTypeValSelected = fileType.get_selectedItem().get_value();
var sbLocationsIDS = new StringBuilder();
for (i = 0; i < LocationIDS.get_items().get_count(); i++) {
sbLocationsIDS.append(LocationIDS.getItem(i).get_value()+ ","); // The problem is here!!!
}
var sbCategoriesIDS = new StringBuilder();
for (i = 0; i < CategoriesIDS.get_items().get_count(); i++) {
sbCategoriesIDS.append(CategoriesIDS.getItem(i).get_value() + ",");
}
var ComparisonsURL = (String.format("https://www.test.com/cgis/{0}/reports/ConnectTorptIncidentsCountByLocationInterval.asp?SessionID={1}&locString={2}&catString={3}&FromDate1={4}&&ToDate1={5}&FromDate2={6}&ToDate2={7}&ExportType={8}", companyCodeVal, SessionID, sbLocationsIDS, sbCategoriesIDS, fromFirstPeriodDateValSelected, toFirstPeriodDateValSelected, fromSecondPeriodDateValSelected, toSecondPeriodDateValSelected, fileTypeValSelected));
openNewTab(ComparisonsURL);
}
}
String.format = function () {
// The string containing the format items (e.g. "{0}")
// will and always has to be the first argument.
var theString = arguments[0];
// start with the second argument (i = 1)
for (var i = 1; i < arguments.length; i++) {
// "gm" = RegEx options for Global search (more than one instance)
// and for Multiline search
var regEx = new RegExp("\\{" + (i - 1) + "\\}", "gm");
theString = theString.replace(regEx, arguments[i]);
}
return theString;
}
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
vars[key] = value;
});
return vars;
}
// Initializes a new instance of the StringBuilder class
// and appends the given value if supplied
function StringBuilder(value) {
this.strings = new Array("");
this.append(value);
}
// Appends the given value to the end of this instance.
StringBuilder.prototype.append = function (value) {
if (value) {
this.strings.push(value);
}
}
// Clears the string buffer
StringBuilder.prototype.clear = function () {
this.strings.length = 1;
}
// Converts this instance to a String.
StringBuilder.prototype.toString = function () {
return this.strings.join("");
}
The problem is your loop is appending , always even for the last item in the loop.
You want to append only for all items other than the last. There are multiple ways to do that, simplest being: check if the current element is the last and if so, do not append ,
var sbLocationsIDS = new StringBuilder();
for (i = 0; i < LocationIDS.get_items().get_count(); i++) {
sbLocationsIDS.append(LocationIDS.getItem(i).get_value()); //append only value
if(i != (LocationIDS.get_items().get_count() -1)) { //if not last item in list
sbLocationsIDS.append(","); //append ,
}
}
There are other ways to do it, and depending on what you want to do with the values in the future, these may be pretty useful. (I see that the append in your code is actually a call to join, so this is actually a simpler version)
Add the values of the list to a array and use Array.join:
var select = document.getElementById("locationId");
var options = select.options;
var optionsArray = [];
if(options) {
for (var i=0; i<=options.length; i++) {
//text is the text displayed in the dropdown.
//You can also use value which is from the value attribute of >option>
optionsArray.push(options[i].text);
}
}
var sbLocationsIDS = optionsArray.join(",");
With JQuery, the above code becomes a bit more simple:
var optionsArray = [];
$("#locationId option").each(function(){
optionsArray.push(options[i].text);
});
var sbLocationsIDS = optionsArray.join(",");
Actually, if you decide yo use JQuery, you can use jquery.map:
(idea from Assigning select list values to array)
$(document).ready(function() {
$("#b").click(function() {
var sbLocationsIDS = jQuery.map($("#locationId option"), function(n, i) {
return (n.value);
}).join(",");
alert(sbLocationsIDS);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="locationId">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button id="b">Click</button>

how to access object property in javascript

function test(results) {
//Populate the ComboBox with unique values
var Gov;
var values = [];
var features = results.features;
var og;
for (i = 0; i < features.length; i++) {
var aGOV = {
"GovName": features[i].attributes.ENG_NAME,
"GovNO": features[i].attributes.GOV_NO,
"Shape": features[i].geometry
}
og = new Option(features[i].attributes.ENG_NAME, aGOV);
var cbx = document.getElementById("cbxGov");
cbx.options.add(og);
}
}
function gov_selection_change()
{
var cbx = document.getElementById("cbxGov");
var itm = cbx.options[cbx.selectedIndex].value.hasOwnProperty("Shape");
}
html code
<select id="cbxGov" onchange="gov_selection_change()">
My problem is i m not able to access property of aGOV in my gov_selection_change() function, it shows it has no such property, itm is false.
The value property of an HTMLOptionElement always returns a DOMString (a.k.a. text), not an object.
So you have to save what you want to access in a lookup dictionary and then use the returned value as a lookup key.
var lookupDictionary = {};
function test(results) {
var lookupKey,
og;
//...
// donĀ“t get the element in the loop
var cbx = document.getElementById("cbxGov");
//...
for (i = 0; i < features.length; i++) {
lookupKey = features[i].attributes.GOV_NO;
lookupDictionary[lookupKey] = {
"GovName": features[i].attributes.ENG_NAME,
"GovNO": features[i].attributes.GOV_NO,
"Shape": features[i].geometry
}
og = new Option(features[i].attributes.ENG_NAME, lookupKey );
cbx.options.add( og );
}
}
function gov_selection_change() {
var cbx = document.getElementById("cbxGov");
var key = cbx.options[cbx.selectedIndex].value;
var itm = lookupDictionary[key].hasOwnProperty("Shape");
}
The variable aGOV is only available in the context of your result() function. If you want to use it from a different function declare it as a global variable.
Example:
var aGOV;
function result()
{
// initialize aGOV
}
function gov_selection_change()
{
// now you can access the aGOV variable
}

Categories