Replacing/Changing one value of an array with JQuery/Javascript - javascript

I have an array that is created within another Javascript call. The array is as follows:
HM_Array1 = [[,11,147,,,,,,,1,1,0,0,0,1,"csiSetBorder(this)","null",,,true,[" Accoun ","",1,0,1],[" Resources ","",1,0,1],[" Reworking ","",1,0,1],[" Account Services ","",1,0,1],[" Education ","",1,0,1],[" App ","",1,0,1]];
I am trying to replace just the '147' value at the top if another element is present within the HTML. So far I haven't had any luck.
This is the code I have been working with thus far.
$(document).ready(function (){
if ($('#impersonationWrapper').length > 0) {
var arr = HM_Array1;
var valChange = HM_Array1[0][2];
if (valChange !== -1) {
HM_array[valChange] = 202;
}
}
else {
}
});
The 147 corresponds to the value of the CSS 'top' value. Unfortunately I have to change this dynamically as I am not allowed to touch the old coding in place. Any help would be greatly appreciated.

I think you want:
var valChange = HM_Array1[0][2];
if (valChange !== -1) {
HM_Array1[0][2] = 202;
}
Your code
HM_array[valChange] = 202;
is the same as:
HM_array[HM_Array1[0][2]] = 202;
which is:
HM_array[147] = 202;
which is setting the value of the 147th item in HM_array as 202. Which isn't what you want. HM_array has only 1 item. And you want to set that item's 2nd item as 202 (replace 147 with 202).

Related

Weird issue with Vue / Javascript variables

I honestly don't even know how to search for this question (what search param to write) but either way its bit weird issue and I am desperate for help.
So I am trying to do something simple, event sends "form-change" and when it does, we set new value in "this.data" object. Fairly simple. I don't expect this.data to be reactive I just want to update it.
// Find our data object which we want to update/change
if (form.field.includes('.')) {
let find = form.field.split('.'), level = this.data;
for (let index = 0; index < find.length; index++) {
if (level[find[index]] !== undefined) {
level = level[find[index]];
} else {
level = undefined;
}
}
if (level !== undefined)
level = setFieldData();
}
This is fairly simple, we have name of field "inspect.book" and when update comes (Event) we just use dots to split into multi tree and update "this.data.inspect.book" to new value. But it does not work. Value does not change.
But the value from actual this.data.inspect.book comes out just fine using:
console.log(level);
However, if I do this:
this.data[ form.field.split( '.' )[ 0 ] ][ form.field.split( '.' )[ 1 ] ] = setFieldData();
It works fine. So "reference" to variable does not work... how is this possible? Looks like a bug in javascript or is it something with vue/reactivity?
Does anyone have better idea how to get this to work?
So you are trying to update form data using to notation ?
i would do something like that :
_update(fieldName, value) {
// We split segments using dot notation (.)
let segments = fieldName.split(".");
// We get the last one
let lastSegment = segments.pop();
// We start with this.data as root
let current = this.data
if(current) {
// We update current by going down each segment
segments.forEach((segment) => {
current = current[segment];
});
// We update the last segment once we are down the correct depth
current[lastSegment] = val;
}
},
if i take your example :
if (form.field.includes('.')) {
let find = form.field.split('.'), level = this.data;
for (let index = 0; index < find.length - 1; index++) {
if (level[find[index]] !== undefined) {
level = level[find[index]];
} else {
level = undefined;
}
}
if (level !== undefined)
level[find.pop()] = setFieldData();
}
i replaced find.length by find.length - 1
and replaced level = setFieldData() by level[find.pop()] = setFieldData()
you should update the property of the object, without actually overriding the value,
because if you override the value, the original value will not get updated.

I'm trying to make an id searcher which does a thing when you input the right id. However, the if statement always runs. Why is this?

I'm trying to make an id searcher which does a thing when you input the right id in google scripts. However, the if statement always runs. Why is this?
The code is here:
function change()
{
var a = SpreadsheetApp.getActive().getRange("Sheet1!A7")
var b = SpreadsheetApp.getActive().getRange("Sheet1!B7")
var c = SpreadsheetApp.getActive().getRange("Sheet1!C7")
var d = SpreadsheetApp.getActive().getRange("Sheet1!D7")
a.copyTo(SpreadsheetApp.getActive().getRange("Sheet1!M4"))
b.copyTo(SpreadsheetApp.getActive().getRange("Sheet1!N4"))
c.copyTo(SpreadsheetApp.getActive().getRange("Sheet1!O4"))
d.copyTo(SpreadsheetApp.getActive().getRange("Sheet1!P4"))
SpreadsheetApp.getActive().getRange("Sheet1!M4").setBackground("white")
SpreadsheetApp.getActive().getRange("Sheet1!N4").setBackground("white")
SpreadsheetApp.getActive().getRange("Sheet1!O4").setBackground("white")
SpreadsheetApp.getActive().getRange("Sheet1!P4").setBackground("white")
}
function myFunction()
{
var id = SpreadsheetApp.getActiveCell()
var idx = id.getValue()
if (idx = 91360136)
{
change()
}
else { id = "invalid id" }
}
Nothing shows up in the debugger at all.
Google Apps Script use javascript, on it a single = is used to assign a primitive or object to a variable. Use == to do an abstract equality comparison or === to do a strict equality comparison.
Change
if (idx = 91360136) {
to
if (idx === 91360136) {
Related Q&A
Using onEdit in Google Spreadsheets to edit cell contents live
How to set a variable based on other variables

move up and down elements in a multiple select not working

I have created an angularjs app with multiple select upon which I am having up and down button , within which when I click up and down button corresponding movement of items should be done within the multiple select, I have a sample stuff which has been done with normal javascript which does the similar thing correctly like as shown in this fiddle, but when I tried to implement the same stuff in AngularJS its not working properly
Can anyone please tell me some solution for this
My code is as given below
JSFiddle
html
<div ng-app='myApp' ng-controller="ArrayController">
<select id="select" size="9" ng-model="persons" ng-options="item as item.name for item in peoples | orderBy:'name'" multiple></select>
<br/>
<button ng-click="moveUp()">Up</button>
<br/>
<button ng-click="moveDown()">Down</button>
<br/>
</div>
script
var app = angular.module('myApp', []);
app.controller('ArrayController', function ($scope) {
$scope.peoples = [{
name: 'Jacob'
}, {
name: 'Sunny'
}, {
name: 'Lenu'
}, {
name: 'Mathew'
}, {
name: 'Ferix'
}, {
name: 'Kitex'
}];
$scope.moveUp = function () {
var select = document.getElementById("select");
var i1=0, i2=1;
while (i2 < select.options.length) {
swapIf(select,i1++,i2++);
}
};
$scope.moveDown = function () {
var select = document.getElementById("select");
var i1=select.options.length-1, i2=i1-1;
while (i1 > 0) {
swapIf(select,i1--,i2--);
}
};
var swapVar = '';
function swapIf(sel,i1,i2) {
if ( ! select[i1].selected && select[i2].selected) {
swapVar = select[i2].text;
select[i2].text = select[i1].text;
select[i1].text = swapVar;
swapVar = select[i2].value;
select[i2].value = select[i1].value;
select[i1].value = swapVar;
select[i1].selected = true;
select[i2].selected = false;
}
}
});
persons will return an array of of whatever items are selected in the list. One solution is to create a for loop that gets the indexOf of each item in the persons array. splice that items out of the peoples array, increment/decrement the index, and splice it back in to the peoples array.
Here is a new moveUp() function that can move up multiple selected items:
$scope.moveUp = function () {
for(var i = 0; i < $scope.persons.length; i++) {
var idx = $scope.peoples.indexOf($scope.persons[i])
console.log(idx);
if (idx > 0) {
var itemToMove = $scope.peoples.splice(idx, 1)
console.log(itemToMove[0])
$scope.peoples.splice(idx-1, 0, itemToMove[0]);
}
}
};
Here is the updated moveDown() function:
$scope.moveDown = function () {
for(var i = 0; i < $scope.persons.length; i++) {
var idx = $scope.peoples.indexOf($scope.persons[i])
console.log(idx);
if (idx < $scope.peoples.length) {
var itemToMove = $scope.peoples.splice(idx, 1)
console.log(itemToMove[0])
$scope.peoples.splice(idx+2, 0, itemToMove[0]);
}
}
};
Here is the Working Demo (Not working so well, just kept for reference - see below)
This solution also maintains the separation between the View and the Controller. The controller has the job of manipulating the data, the view displays that data. This way we can avoid any uncomely entanglement. DOM manipulations from within the controller are incredibly difficult to test.
EDIT after some tinkering:
So my previous solution worked in some cases but would perform oddly with different select combinations. After some digging, I found it necessary to add track by:
<select id="select" size="9" ng-model="persons" ng-options="item as item.name for item in peoples track by item.name" multiple>
It seems the select would return the persons object with arbitrary selection orders and this was messing things up, especially after you clicked a few times, it seemed to get confused about where things were.
Additionally, I had to clone and reverse the persons array when moving items down because when adding track by item.name it returns the items in order, but if you try to iterate through the array, moving each one down, you are potentially impacting the location of other items in the array (further producing unpredictable behavior). So we need to start from the bottom and work our way up when moving multiple items down.
Here is a solution in which I seem to have eliminated any unpredictable behavior when making multiple arbitrary selections:
Working Demo
EDIT:
One bug I have found is that weird things happen when you move multiple selected items all the way up or down, and then try to move it that direction one more time. Any further movement without reselecting produces unpredictable results.
EDIT:
The unpredictable behavior mentioned in the previous edit was because the functions were seeing that, although the first item was in it's final position, the second, third, fourth, etc. items were not in an end position, and thus it tried to move them which led to crazy re-ordering of items that were already pushed all the one to the top or bottom. In order to solve this I set a var that would track the position of the previously moved item. If the current item was found to be in the adjacent position it would simply leave it there and move on.
The final functions look something like this:
$scope.moveUp = function () {
var prevIdx = -1;
var person = $scope.persons.concat();
console.log($scope.persons);
for(var i = 0; i < $scope.persons.length; i++) {
var idx = $scope.peoples.indexOf($scope.persons[i])
console.log(idx);
if (idx-1 === prevIdx) {
prevIdx = idx
} else if (idx > 0) {
var itemToMove = $scope.peoples.splice(idx, 1)
console.log(itemToMove[0])
$scope.peoples.splice(idx-1, 0, itemToMove[0]);
}
}
};
(Hopefully) Final Demo
EDIT:
I enjoyed this problem and wanted to have a better solution in case there were duplicate list items. This was fairly easy to solve by giving each object in the array a unique id key, and then changing track by item.name to track by item.id, and all works as before.
Working Demo for Duplicates
Demo
You need to update your swapIf implementation so that it swaps the model, not options from the view:
function swapIf(sel,i1,i2) {
if ( ! select[i1].selected && select[i2].selected) {
var obj1 = $scope.peoples[i1];
var obj2 = $scope.peoples[i2];
$scope.peoples[i2] = obj1;
$scope.peoples[i1] = obj2;
select[i1].selected = true;
select[i2].selected = false;
}
}
Also, remove the orderBy in the view, and initialize the ordering in the controller using the $filter service. The reason you need to do this is because the list is re-ordered whenever the user clicks the up/down button.

JavaScript array search to return index position for 2 element search

I need to search a JSON set for 2 elements of an array. If a match is found for these 2 elements, I need the index of this position. And once I have this index, I can use this to access a different property in this same array position.
Below is sample of what I have. If you look at line 22, I am hard-coding the array position to 1. This is the value I dynamically need depending on what I pass into my getModelID() function.
http://codepen.io/bdang/pen/pJvmox/?editors=101
function getModelID(extClr, intClr) {
var colorLockDatesAr = lockDates.Models[0].Colors,
colorLockDatesCount = colorLockDatesAr.length;
for(var i = 0; i < colorLockDatesCount; i++) {
if(colorLockDatesAr[i].ExtColorCd == extClr && colorLockDatesAr[i].IntColorCd == intClr) {
$('#modelID').html(colorLockDatesAr[1].ModelID);
}
}
}
getModelID('BK', 'BK'); // should return Model 1
getModelID('BK', 'WH'); // should return Model 2
getModelID('WH', 'BK'); // should return Model 3
I have looked through various forums and many issues I've found are related issues but none specific to what I need. Any help with this would be greatly appreciated.
Just pass i
$('#modelID').html(colorLockDatesAr[i].ModelID);
http://codepen.io/miguelmota/pen/xGbNVG

jQuery grep return on Multidimensional Array

I am learning jQuery and am having issues trying to figure out how to select elements in a multidimensional array. I have a select list with database IDs and I want to set a var with the cost field in the database according to the id that selected. I have all the pieces except for translating the selected ID to a cost. Can someone please help me with getting this right please?
var rangeListData = [{"idrange_list":"1","range_cost":"0","target_range_name":"Self Only"},{"idrange_list":"2","range_cost":"1","target_range_name":"1 Space"},{"idrange_list":"3","range_cost":"2","target_range_name":"2 Spaces"},{"idrange_list":"4","range_cost":"3","target_range_name":"3 Spaces"},{"idrange_list":"5","range_cost":"4","target_range_name":"4 Spaces"},{"idrange_list":"6","range_cost":"5","target_range_name":"5 Spaces"}];
$('#slctPowerTarget').change(function () {
var targetID = $('#slctPowerTarget').val();
var cost $.grep(rangeListData, function(e) { return e.idrange_list == targetID }); // this is the line that is wrong
$('#spanTotalEffectsCost').text(cost);
});
If I put targetID in where cost is it lists fine. But when I try to look this up nothing happens. It is not right somehow and I am not sure what else to try. I think I get how idrange_list == targetID is supposed to match them but not sure how to call the related range_cost.
Thanks for any help you can offer! I read through the docs at jquery.com but can't seem to wrap my head around them.
You can do this :-
// Get the Multidimensional Array first
var data = $.grep(rangeListData, function (e) {
return e.idrange_list === targetID
});
// Get the range cost from the array
var cost = data[0].range_cost;
// Check the value in console for debugging purpose
console.log(cost);
Here is the final code. I also added an IF clause in there in case they select the default setting. This way it will reset instead of tossing an error and keeping page calculations working no matter if they change the drop downs or go back to "Select..."
$('#slctPowerRange').change(function () {
var rangeID = $('#slctPowerRange').val();
if (rangeID > 0) {
var rdata = $.grep(rangeListData, function (e) {
return e.idrange_list === rangeID
});
var rcost = rdata[0].range_cost;
}
else {
var rcost = 0 ;
}
$('#hdnRangeCost').val(rcost);
});

Categories

Resources