Javascript SetTimeOut function Does Not Work Somehow - javascript

My system fatches data every 500 ms and my screen is full of html tables apart from each other . And every cell has unique key attribute. I am caching all of them anyway.
I have a global JavaScript object(_cellColorTimeouts) which contains settimeout functions for cellElements of tableRows that I mentioned above. After caching of cells, system creates timeout functions which is to wipe css out for spesific cell (in 3000ms).
In code block below uiElementKey_X and uiElementKey_Y are exact same but cached like are different. Adding unique suffix into table id makes them different. This proccess is done for row and cell items aswell.
example of _cellColorTimeouts data is
//array object keys are names of unique cell items.
_cellColorTimeouts = [uiElementKey_X_1, uiElementKey_X_2, uiElementKey_X_3,
uiElementKey_Y_1, uiElementKey_X_2, uiElementKey_Y_3];
.
. //does somethings to change cell colour
.
//after 3 seconds i need to clear css of this cell without looping the dom so i do it via cached dom.
if (_cellColorTimeouts.hasOwnProperty(uiElementKey) && _cellColorTimeouts[uiElementKey] != null) {
clearTimeout(_cellColorTimeouts[uiElementKey]);
_cellColorTimeouts[uiElementKey] = null;
}
_cellColorTimeouts[uiElementKey] = setTimeout(function () {
clearColourOfCell(cell);
}, 3000);
}
function clearColourOfCell(cell) {
cell.style.backgroundColor = cell.rowBGColour;
cell.style.color = "black";
_cellColorTimeouts[cell.uiElementKey] == null;
clearTimeout(_cellColorTimeouts[cell.uiElementKey]);
}
So the problem is settimeout function is not working for the first table but second is totally fine. I have checked is there any settimeout function return id from global, yes it has. For the first table somehow it does not work. I know this question is too unique for my case but any idea will be preciated?
---- EDIT ---- FULL FUNCTION UNCUT VERSION -----
function setWidgetData(widgetId, rowId, colId, value, colIndex) {
"use strict";
// check colIndex
if (colIndex === undefined || colIndex === null) {
colIndex = 0;
}
// loop on ui tables
var uiTables = _widgetUIElements[widgetId];
//var timeout;
for (var tableId in uiTables) {
var uiTable = uiTables[tableId];
var uiElementKey = tableId + "#" + rowId + "#" + colId + "#" + colIndex;
var cellCachedObject = uiTable[uiElementKey];
// check cell
if (cellCachedObject == undefined) {
//console.log("cell is undefined : " + "widgetId : " + widgetId + " - " + "rowId : " + rowId + " - " + "colId : " + colId + " - " + "colIndex : " + colIndex);
}
else {
// get cell
var cell = cellCachedObject["domElement"];
// set sell value
var cellValue = value;
// is value numeric? it means we will make some conversions on value
if (isNumeric(cellValue)) {
var canPaint = false;
// check cell entity
switch (cellCachedObject["entity"]) {
// date-time?
case "DATETIME":
// convert unix date time to readable date time
cellValue = new Date(fixDecimalSeparator(cellValue) * 1000);
cellValue = fixDateTimeDigits((cellValue.getDate())) + "/" + fixDateTimeDigits((cellValue.getMonth() + 1)) + " " + fixDateTimeDigits(cellValue.getHours()) + ":" + fixDateTimeDigits(cellValue.getMinutes());
break;
// date?
case "DATE":
// convert unix date time to readable date time
cellValue = new Date(fixDecimalSeparator(cellValue) * 1000);
cellValue = fixDateTimeDigits((cellValue.getDate())) + "/" + fixDateTimeDigits((cellValue.getMonth() + 1));
break;
// numeric?
case "NR":
// fix "," character in value
cellValue = fixDecimalSeparator(cellValue);
//just format the presicion
cellValue = number_format(cellValue, cellCachedObject["precision"], '.', ',');
canPaint = true;
break;
// other?
default:
// fix "," character in value
cellValue = fixDecimalSeparator(cellValue);
// if cell is number, no entity conversion
// entity convertion
cellValue = entityConverter(cellCachedObject["entity"], cellCachedObject["entityTo"], cellValue);
cellValue = new Number(cellValue).toFixed(cellCachedObject["precision"]);
// if widget currency is not USD. it means user selected currency from currency list or default user currency
if (cellCachedObject["isConvertable"]) {
// this scoop is not active with the new xml. if FOREX1 widget entity is RECIPCUR but never should not be
if (cellCachedObject["widgetIsFOREX1"]) {
cellValue = _currencyConverter.convertTrend(cellValue, cellCachedObject.currencyValueType, cellCachedObject["currencyTo"], cellCachedObject["rowId"], cellValue);
}
else {
cellValue = _currencyConverter.convert(cellValue, cellCachedObject["currency"], null, cellCachedObject["precision"]);
}
}
canPaint = true;
}
// if it is not date time
if (canPaint) {
// get current value of cell
var currentValue = cell.getAttribute("currentValue");
// check current value of cell make them coloured.
if (currentValue !== undefined) {
// new value is bigger than old value
var newVal = parseFloat(value);
var oldVal = parseFloat(currentValue);
var rowBGColour = cellCachedObject["rowBGColor"];
cell.rowBGColour = rowBGColour;
cell.uiElementKey = uiElementKey;
if (newVal > oldVal) {
//cell.css({ "background-color": "Green", "color": "White" });
cell.style.backgroundColor = "green";
cell.style.color = "white";
}
// new value is smaller than old value
if (newVal < oldVal) {
//cell.css({ "background-color": "Red", "color": "White" });
cell.style.backgroundColor = "red";
cell.style.color = "white";
}
if (_cellColorTimeouts.hasOwnProperty(uiElementKey) && _cellColorTimeouts[uiElementKey] != null) {
clearTimeout(_cellColorTimeouts[uiElementKey]);
_cellColorTimeouts[uiElementKey] = null;
}
_cellColorTimeouts[uiElementKey] = setTimeout(function () {
return function () {
clearColourOfCell(cell);
};
} (cell), 3000);
newVal = oldVal = rowBGColour = null;
}
currentValue = null;
}
canPaint = null;
// set new value as a current value
cell.setAttribute("currentValue", value);
}
cell.innerHTML = '';
cell.innerHTML = cellValue;
cellValue = null;
}
uiTable = uiElementKey = cellCachedObject = null;
}
uiTables = null;
}

You didn't post enough code for me to know for sure that this is the problem, but it's a good bet:
_cellColorTimeouts[uiElementKey] = setTimeout(function () {
return function() {
clearColourOfCell(cell);
};
}(cell), 3000);
By setting up the timeout handler like that, you ensure that the handler has its own private copy of that "cell" variable, so that no matter how "cell" is changed before the handler is finally invoked, that copy will retain the correct value.

Related

Delete all empty cells in a column then shift all non empty cells up

Here is my code:
var ct = 0;
var sheet = SpreadsheetApp.getActiveSheet();
var cell = sheet.getCurrentCell();
var cellcol = cell.getColumn();
var cellrow = cell.getRow()
var notate = cell.getA1Notation();
var temp, letter = '';
var solved = new Array()
var pend = new Array()
var cellcol1 = cellcol + 1;
var p;
function copycell1() {
getFirstEmptyRowByColumnArray();
cell.copyTo(sheet.getRange(ct,cellcol,1,1))
cell.clearContent();
}
function getFirstEmptyRowByColumnArray() {
columnToLetter(cellcol)
var column = sheet.getRange(letter + ':' + letter);
var values = column.getValues();
while ( values[ct] && values[ct][0] !== "" ) {
ct++;
}
ct++
}
function getFirstEmptyRowByColumnArray2() {
columnToLetter(cellcol);
var cellrow = cell.getRow();
var column = sheet.getRange(letter + cellrow + ':' + letter);
var values = column.getValues();
while ( values[ct] && values[ct][0] !== "" ) {
ct++;
}
}
function columnToLetter(column)
{
while (column > 0)
{
temp = (column - 1) % 26;
letter = String.fromCharCode(temp + 65) + letter;
column = (column - temp - 1) / 26;
}
return letter;
}
function totalSolved() {
getFirstEmptyRowByColumnArray2()
var compacolumn = sheet.getRange(letter + cellrow + ':' + letter + (ct+cellrow));
var valuesSolved = compacolumn.getValues();
solved = valuesSolved
}
function totalPending() {
letter = '';
ct = 0;
cellcol = cellcol + 1;
getFirstEmptyRowByColumnArray2()
cellrow = cell.getRow();
var compacolumn = sheet.getRange(letter + cellrow + ':' + letter + (ct + cellrow));
var valuesPend = compacolumn.getValues();
pend = valuesPend
}
function compa() {
var i;
var o;
totalSolved();
totalPending();
for ( i = 0; i < pend.length; i++ ) {
for (o = 0; o < solved.length; o++) {
if (pend[i].toString() == solved[o].toString()) {
sheet.getRange(i+cellrow,cellcol1).clearContent();
}
else {
}
}
}
clearemp();
clearemp();
clearemp();
}
function clearemp() {
lastRowForColumn(cellcol1)
for (var i = 0; i < p; i++){
if((sheet.getRange(letter+(cellrow+i)).getValue()) == "")
{
Logger.log(sheet.getRange(letter+(cellrow+i)).getA1Notation());
sheet.getRange(letter+(cellrow+i)).deleteCells(SpreadsheetApp.Dimension.ROWS);
}
}
}
function lastRowForColumn(column){
var numRows = sheet.getLastRow();
Logger.log("numRows is " + numRows)
var data = sheet.getRange(1, column, numRows).getValues();
Logger.log("data is " + data)
Logger.log("data.length is " + data.length)
for(p = data.length - 1 ; p >= 0 ; p--){
if (data[p][0] != null && data[p][0] != ""){
Logger.log ("p is " + p)
return p + 1;
}
}
}
function test() {
Logger.log("cellcol is " + cellcol1)
lastRowForColumn(cellcol1)
Logger.log("p is " + p)
}
The function I'm talking about is compa().
The specific function that deletes the cells is clearemp(). But whenever I do it it is still not complete and I am at a loss on what to do
CONTEXT: I am working on comparing two lists and then removing the equal cells on the 2nd column and then shifting the cells up.
function delcels(col=1) {
const ss=SpreadsheetApp.getActive();
const sh=ss.getSheetByName('Sheet1');
const rg=sh.getRange(1,col,sh.getLastRow());
const c1=rg.getValues().filter((e)=>!(e===""));//thanks to iansedano
rg.clearContent();
sh.getRange(1,col,c1.length,1).setValues(c1);
}
A possible solution
There are a few approaches, but here is one, that is essentially the same as Cooper's, except that it doesn't clear values that are 0. Only if the cell is empty, i.e. "" will it clear the cell.
/**
* Clears empty cells in column
*
* #param columnToClear - the column that should be cleared, defaults to 1
* #param sheetName - the name of the sheet, defaults to "Sheet1"
*/
function clearBlanks(columnToClear = 1, sheetName = "Sheet1") {
const file = SpreadsheetApp.getActive();
const sheet = file.getSheetByName(sheetName);
const range = sheet.getRange(1, columnToClear, sheet.getLastRow(), 1);
const output = range.getValues().filter(e => !(e[0] === ""));
range.clearContent();
const outputRange = sheet.getRange(1, columnToClear, output.length, 1)
outputRange.setValues(output)
}
This gets the whole range into memory as a 2D array.
Uses filter to take out any values that are strictly equal === to and empty string. So it will not clear 0 values.
Clears the whole column, and pastes in the filtered array.
Filter
This is called on an array
array.filter(function)
You need to pass in a function that will return either a True or False value. The filter will go through each element and if it gets False then it will remove that element. In the example above, its passed in as an arrow function. When its an arrow function, if its on one line, you don't need to include the return statement.
There are a few useful functions that are like this. For example, forEach and map that can be very useful for the types of operation you are doing.
Reference
filter

How I can get object from another function

I'm trying to do a Shopping cart with HTML and JS. So I'm using (https://www.smashingmagazine.com/2019/08/shopping-cart-html5-web-storage/).
In my function save(), I have,
`function save(id, title, price) {
// var button = document.getElementById('button');
// button.onclick=function(){
// var test = localStorage.setItem('test', id);
window.location.href='/panier'
var obj = {
title: title,
price: price
};
localStorage.setItem(id, JSON.stringify(obj));
var test = localStorage.getItem(id);
var getObject = JSON.parse(test);
console.log(getObject.title);
console.log(getObject.price);
}`
so to get "title for example I don't have problem in my function save(), but in my function doShowAll(),
function CheckBrowser() {
if ('localStorage' in window && window['localStorage'] !== null) {
// We can use localStorage object to store data.
return true;
} else {
return false;
}
}
function doShowAll() {
if (CheckBrowser()) {
var key = "";
var id = localStorage.getItem(id);
var list = "<tr><th>Item</th><th>Value</th></tr>\n";
var i = 0;
//For a more advanced feature, you can set a cap on max items in the cart.
for (i = 0; i <= localStorage.length-1; i++) {
key = localStorage.key(i);
list += "<tr><td>" + key + "</td>\n<td>"
+ localStorage.getItem(key) + "</td></tr>\n";
}
//If no item exists in the cart.
if (list == "<tr><th>Item</th><th>Value</th></tr>\n") {
list += "<tr><td><i>empty</i></td>\n<td><i>empty</i></td></tr>\n";
}
//Bind the data to HTML table.
//You can use jQuery, too.
document.getElementById('list').innerHTML = list;
} else {
alert('Cannot save shopping list as your browser does not support HTML 5');
}
}
I can't to get my object.
I have tried:
if (CheckBrowser()) {
var key = "";
var id = localStorage.getItem(id);
var getObject = JSON.parse(test);
}
var list = "<tr><th>Item</th><th>Value</th></tr>\n";
var i = 0;
//For a more advanced feature, you can set a cap on max items in the cart.
for (i = 0; i <= localStorage.length-1; i++) {
key = localStorage.key(i);
list += "<tr><td>" + key + "</td>\n<td>" + getObject.title
+ localStorage.getItem(key) + "</td></tr>\n";
}
but when I add something else than key or localStorage.getItem(key) in "list +=" nothing is displayed in my html view.
So I just Want to display data from my object in the PHP array in doShowAll() function.
Hoping to have clear and wainting a reply. Thank you

Brainlabs adwords script remove firstpagemaxbid restriction

Can some body help me modify this script.
The purpose of the script is to change bids for the keywords based on average position. One of the assumptions that the script has is that it sets a firstpagebid for the keyword but it won't allow for the bid to go below the firstpagebid even if the position is too high.
Is there a way to remove this restriction? so basically if the new cpc calculated is lower than the first page bid then it allows for the new cpc to be lower than the firstpage bid.
/**
*
* Average Position Bidding Tool
*
* This script changes keyword bids so that they target specified positions,
* based on recent performance.
*
* Version: 1.5
* Updated 2015-09-28 to correct for report column name changes
* Updated 2016-02-05 to correct label reading, add extra checks and
* be able to adjust maximum bid increases and decreases separately
* Updated 2016-08-30 to correct label reading from reports
* Updated 2016-09-14 to update keywords in batches
* Updated 2016-10-26 to avoid DriveApp bug
* Google AdWords Script maintained on brainlabsdigital.com
*
**/
// Options
var maxBid = 14.50;
// Bids will not be increased past this maximum.
var minBid = 3.0;
// Bids will not be decreased below this minimum.
var firstPageMaxBid = 10.00;
// The script avoids reducing a keyword's bid below its first page bid estimate. If you think
// Google's first page bid estimates are too high then use this to overrule them.
var dataFile = "AveragePositionData.txt";
// This name is used to create a file in your Google Drive to store today's performance so far,
// for reference the next time the script is run.
var useFirstPageBidsOnKeywordsWithNoImpressions = true;
// If this is true, then if a keyword has had no impressions since the last time the script was run
// its bid will be increased to the first page bid estimate (or the firsPageMaxBid if that is smaller).
// If this is false, keywords with no recent impressions will be left alone.
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Advanced Options
var bidIncreaseProportion = 0.20;
var bidDecreaseProportion = 0.25;
var targetPositionTolerance = 0.3;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function main() {
var fieldJoin = ",";
var lineJoin = "$";
var idJoin = "#";
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
/*var files = DriveApp.getFilesByName(dataFile);
if (!files.hasNext()) {
var file = DriveApp.createFile(dataFile,"\n");
Logger.log("File '" + dataFile + "' has been created.");
} else {
var file = files.next();
if (files.hasNext()) {
Logger.log("Error - more than one file named '" + dataFile + "'");
return;
}
Logger.log("File '" + dataFile + "' has been read.");
}*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Get the current date/time
var currentTime = new Date(Utilities.formatDate(new Date(), AdWordsApp.currentAccount().getTimeZone(), "MMM dd,yyyy HH:mm:ss"));
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var hourOfDay = currentTime.getHours();
var dayOfWeek = days[currentTime.getDay()]; //Added on 9/21/2015
// Prevent adjustments if not in between 8am and 11pm and Diffrent running time by date - Added on 9/21/2015 (important allows to set time based on day)
switch (dayOfWeek) {
case 'Monday':
case 'Tuesday':
case 'Wednesday':
case 'Thursday':
case 'Friday':
if (hourOfDay < 8 || hourOfDay >= 21) {
Logger.log("Not the Right Time");
return;
}
break;
case 'Saturday':
case 'Sunday':
if (hourOfDay < 8 || hourOfDay >= 18) {
Logger.log("Not the Right Time");
return;
}
break;
}
Logger.log("Right Time");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
var labelIds = [];
var labelIterator = AdWordsApp.labels()
.withCondition("KeywordsCount > 0")
.withCondition("LabelName CONTAINS_IGNORE_CASE 'Position '")
.get();
while (labelIterator.hasNext()) {
var label = labelIterator.next();
if (label.getName().substr(0,"position ".length).toLowerCase() == "position ") {
labelIds.push(label.getId());
}
}
if (labelIds.length == 0) {
Logger.log("No position labels found.");
return;
}
Logger.log(labelIds.length + " position labels have been found.");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
var keywordData = {
//UniqueId1: {LastHour: {Impressions: , AveragePosition: }, ThisHour: {Impressions: , AveragePosition: },
//CpcBid: , FirstPageCpc: , MaxBid, MinBid, FirstPageMaxBid, PositionTarget: , CurrentAveragePosition:,
//Criteria: }
}
var ids = [];
var uniqueIds = [];
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
var report = AdWordsApp.report(
'SELECT Id, Criteria, AdGroupId, AdGroupName, CampaignName, Impressions, AveragePosition, CpcBid, FirstPageCpc, Labels, BiddingStrategyType ' +
'FROM KEYWORDS_PERFORMANCE_REPORT ' +
'WHERE Status = ENABLED AND AdGroupStatus = ENABLED AND CampaignStatus = ENABLED ' +
'AND LabelIds CONTAINS_ANY [' + labelIds.join(",") + '] ' +
'AND AdNetworkType2 = SEARCH ' +
'AND Device NOT_IN ["HIGH_END_MOBILE"] ' +
'DURING TODAY'
);
var rows = report.rows();
while(rows.hasNext()){
var row = rows.next();
if (row["BiddingStrategyType"] != "cpc") {
if (row["BiddingStrategyType"] == "Enhanced CPC"
|| row["BiddingStrategyType"] == "Target search page location"
|| row["BiddingStrategyType"] == "Target Outranking Share"
|| row["BiddingStrategyType"] == "None"
|| row["BiddingStrategyType"] == "unknown") {
Logger.log("Warning: keyword " + row["Criteria"] + "' in campaign '" + row["CampaignName"] +
"' uses '" + row["BiddingStrategyType"] + "' rather than manual CPC. This may overrule keyword bids and interfere with the script working.");
} else {
Logger.log("Warning: keyword " + row["Criteria"] + "' in campaign '" + row["CampaignName"] +
"' uses the bidding strategy '" + row["BiddingStrategyType"] + "' rather than manual CPC. This keyword will be skipped.");
continue;
}
}
var positionTarget = "";
if (row["Labels"].trim() == "--") {
continue;
}
var labels = JSON.parse(row["Labels"].toLowerCase()); // Labels are returned as a JSON formatted string
for (var i=0; i<labels.length; i++) {
if (labels[i].substr(0,"position ".length) == "position ") {
var positionTarget = parseFloat(labels[i].substr("position ".length-1).replace(/,/g,"."),10);
break;
}
}
if (positionTarget == "") {
continue;
}
if (integrityCheck(positionTarget) == -1) {
Logger.log("Invalid position target '" + positionTarget + "' for keyword '" + row["Criteria"] + "' in campaign '" + row["CampaignName"] + "'");
continue;
}
ids.push(parseFloat(row['Id'],10));
var uniqueId = row['AdGroupId'] + idJoin + row['Id'];
uniqueIds.push(uniqueId);
keywordData[uniqueId] = {};
keywordData[uniqueId]['Criteria'] = row['Criteria'];
keywordData[uniqueId]['ThisHour'] = {};
keywordData[uniqueId]['ThisHour']['Impressions'] = parseFloat(row['Impressions'].replace(/,/g,""),10);
keywordData[uniqueId]['ThisHour']['AveragePosition'] = parseFloat(row['AveragePosition'].replace(/,/g,""),10);
keywordData[uniqueId]['CpcBid'] = parseFloat(row['CpcBid'].replace(/,/g,""),10);
keywordData[uniqueId]['FirstPageCpc'] = parseFloat(row['FirstPageCpc'].replace(/,/g,""),10);
setPositionTargets(uniqueId, positionTarget);
}
Logger.log(uniqueIds.length + " labelled keywords found");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
setBidChange();
setMinMaxBids();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
/* var currentHour = parseInt(Utilities.formatDate(new Date(), AdWordsApp.currentAccount().getTimeZone(), "HH"), 10);
if (currentHour != 0) {
var data = file.getBlob().getDataAsString();
var data = data.split(lineJoin);
for(var i = 0; i < data.length; i++){
data[i] = data[i].split(fieldJoin);
var uniqueId = data[i][0];
if(keywordData.hasOwnProperty(uniqueId)){
keywordData[uniqueId]['LastHour'] = {};
keywordData[uniqueId]['LastHour']['Impressions'] = parseFloat(data[i][1],10);
keywordData[uniqueId]['LastHour']['AveragePosition'] = parseFloat(data[i][2],10);
}
}
}*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
findCurrentAveragePosition();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//Batch the keyword IDs, as the iterator can't take them all at once
var idBatches = [];
var batchSize = 5000;
for (var i=0; i<uniqueIds.length; i += batchSize) {
idBatches.push(uniqueIds.slice(i,i+batchSize));
}
Logger.log("Updating keywords");
// Update each batch
for (var i=0; i<idBatches.length; i++) {
try {
updateKeywords(idBatches[i]);
} catch (e) {
Logger.log("Error updating keywords: " + e);
Logger.log("Retrying after one minute.");
Utilities.sleep(60000);
updateKeywords(idBatches[i]);
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Logger.log("Writing file.");
// var content = resultsString();
// file.setContent(content);
Logger.log("Finished.");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Functions
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function integrityCheck(target){
var n = parseFloat(target, 10);
if(!isNaN(n) && n >= 1){
return n;
}
else{
return -1;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function setPositionTargets(uniqueId, target){
if(target !== -1){
keywordData[uniqueId]['HigherPositionTarget'] = Math.max(target-targetPositionTolerance, 1);
keywordData[uniqueId]['LowerPositionTarget'] = target+targetPositionTolerance;
}
else{
keywordData[uniqueId]['HigherPositionTarget'] = -1;
keywordData[uniqueId]['LowerPositionTarget'] = -1;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function bidChange(uniqueId){
var newBid = -1;
if(keywordData[uniqueId]['HigherPositionTarget'] === -1){
return newBid;
}
var cpcBid = keywordData[uniqueId]['CpcBid'];
var minBid = keywordData[uniqueId]['MinBid'];
var maxBid = keywordData[uniqueId]['MaxBid'];
if (isNaN(keywordData[uniqueId]['FirstPageCpc'])) {
Logger.log("Warning: first page CPC estimate is not a number for keyword '" + keywordData[uniqueId]['Criteria'] + "'. This keyword will be skipped");
return -1;
}
var firstPageBid = Math.min(keywordData[uniqueId]['FirstPageCpc'], keywordData[uniqueId]['FirstPageMaxBid'], maxBid);
var currentPosition = keywordData[uniqueId]['CurrentAveragePosition'];
var higherPositionTarget = keywordData[uniqueId]['HigherPositionTarget'];
var lowerPositionTarget = keywordData[uniqueId]['LowerPositionTarget'];
var bidIncrease = keywordData[uniqueId]['BidIncrease'];
var bidDecrease = keywordData[uniqueId]['BidDecrease'];
if((currentPosition > lowerPositionTarget) && (currentPosition !== 0)){
var linearBidModel = Math.min(2*bidIncrease,(2*bidIncrease/lowerPositionTarget)*(currentPosition-lowerPositionTarget));
var newBid = Math.min((cpcBid + linearBidModel), maxBid);
}
if((currentPosition < higherPositionTarget) && (currentPosition !== 0)) {
var linearBidModel = Math.min(2*bidDecrease,((-4)*bidDecrease/higherPositionTarget)*(currentPosition-higherPositionTarget));
var newBid = Math.max((cpcBid-linearBidModel),minBid);
if (cpcBid > firstPageBid) {
var newBid = Math.max(firstPageBid,newBid);
}
}
if((currentPosition === 0) && useFirstPageBidsOnKeywordsWithNoImpressions && (cpcBid < firstPageBid)){
var newBid = firstPageBid;
}
if (isNaN(newBid)) {
Logger.log("Warning: new bid is not a number for keyword '" + keywordData[uniqueId]['Criteria'] + "'. This keyword will be skipped");
return -1;
}
return newBid;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function findCurrentAveragePosition(){
for(var x in keywordData){
if(keywordData[x].hasOwnProperty('LastHour')){
keywordData[x]['CurrentAveragePosition'] = calculateAveragePosition(keywordData[x]);
} else {
keywordData[x]['CurrentAveragePosition'] = keywordData[x]['ThisHour']['AveragePosition'];
}
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function calculateAveragePosition(keywordDataElement){
var lastHourImpressions = keywordDataElement['LastHour']['Impressions'];
var lastHourAveragePosition = keywordDataElement['LastHour']['AveragePosition'];
var thisHourImpressions = keywordDataElement['ThisHour']['Impressions'];
var thisHourAveragePosition = keywordDataElement['ThisHour']['AveragePosition'];
if(thisHourImpressions == lastHourImpressions){
return 0;
}
else{
var currentPosition = (thisHourImpressions*thisHourAveragePosition-lastHourImpressions*lastHourAveragePosition)/(thisHourImpressions-lastHourImpressions);
if (currentPosition < 1) {
return 0;
} else {
return currentPosition;
}
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function keywordUniqueId(keyword){
var id = keyword.getId();
var idsIndex = ids.indexOf(id);
if(idsIndex === ids.lastIndexOf(id)){
return uniqueIds[idsIndex];
}
else{
var adGroupId = keyword.getAdGroup().getId();
return adGroupId + idJoin + id;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function setMinMaxBids(){
for(var x in keywordData){
keywordData[x]['MinBid'] = minBid;
keywordData[x]['MaxBid'] = maxBid;
keywordData[x]['FirstPageMaxBid'] = firstPageMaxBid;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function setBidChange(){
for(var x in keywordData){
keywordData[x]['BidIncrease'] = keywordData[x]['CpcBid'] * bidIncreaseProportion/2;
keywordData[x]['BidDecrease'] = keywordData[x]['CpcBid'] * bidDecreaseProportion/2;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function updateKeywords(idBatch) {
var keywordIterator = AdWordsApp.keywords()
.withIds(idBatch.map(function(str){return str.split(idJoin);}))
.get();
while(keywordIterator.hasNext()){
var keyword = keywordIterator.next();
var uniqueId = keywordUniqueId(keyword);
var newBid = bidChange(uniqueId);
if(newBid !== -1){
keyword.setMaxCpc(newBid);
}
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
/*function resultsString(){
var results = [];
for(var uniqueId in keywordData){
var resultsRow = [uniqueId, keywordData[uniqueId]['ThisHour']['Impressions'], keywordData[uniqueId]['ThisHour']['AveragePosition']];
results.push(resultsRow.join(fieldJoin));
}
return results.join(lineJoin);
}*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
}
As I understand, the script increases the cpcBid when the current average position is too high, and decreases it when the position is too low.
But when the bid is decreased and the previous bid is more than firstPageBid, the new bid will not decrease below firstPageBid.
Remove
if (cpcBid > firstPageBid) {
var newBid = Math.max(firstPageBid,newBid);
}
to allow your new bid to go lower than firstPageBid.

Append two values in JavaScript

var descriptionInput;
var tbl = $(document.getElementById('21.125-mrss-cont-none-content'));
tbl.find('tr').each(function () {
$(this).find("input[name$='6#if']").keypress(function (e) {
if (e.which == 13) {
descriptionInput = $(this).val();
$(this).val(descriptionInput);
$(document.getElementById('__AGIM0:U:1:4:2:1:1::0:14')).val(descriptionInput);
}
console.log(descriptionInput);
});
});
});
The function above gets an input value from a field in a set of rows using jQuery .val()
var table = document.getElementById('DYN_6000-LISTSAPLMEGUI-tab');
var t = table.rows.length;
//getting current blank cell ID and upping the blank cell ID to the new last cell
var new_cell_id = table.rows.item(t-1).id;
var old_cell_id = "DYN_6000-LISTSAPLMEGUI-key-" + t;
table.rows.item(t - 1).id = old_cell_id;
table.rows.item(t - 1).onmouseover = function () { showItemDetailDropDown_hover(old_cell_id); };
table.rows.item(t - 1).onmouseout = function () { showItemDetailDropDown_hover(old_cell_id); };
table.rows.item(t - 1).onclick = function () { showItemDetailDropDown_click(old_cell_id); };
//create new row and table
var drop_down_height = document.getElementById('DYN_6000-LISTSAPLMEGUI-scrl').style.height;
document.getElementById('DYN_6000-LISTSAPLMEGUI-scrl').style.height = (parseInt(drop_down_height.replace("px", "")) + 18) + "px";
var new_row = table.insertRow(t-1);
var new_cell = new_row.insertCell(0);
new_row.insertCell(1);
//set new row and cell properties
new_row.id = new_cell_id;
new_row.classList.add('urNoUserSelect');
new_row.style.width = "100%";
new_row.style.height = "18px";
new_row.onmouseover = function () { showItemDetailDropDown_hover(new_cell_id); };
new_row.onmouseout = function () {showItemDetailDropDown_hover(new_cell_id); };
new_row.onclick = function () {showItemDetailDropDown_click(new_cell_id);};
new_cell.classList.add('urIlb2I');
new_cell.classList.add('urColorTxtStandard');
var new_item = t;
new_cell.innerHTML = "[ " + new_item + " ]";
var zyx = "grid#21.125#" + row + ",2#if";
document.getElementById(zyx).value = new_item;
document.getElementById('__AGIM0:U:1:4:2:1:1::0:14').value = new_cell.innerHTML;
checkButton('keyboard');
This JS function is part of an if else statement that checks if there is a new value in each row and adds a sequential number to a dropdown item menu below the table. My question is: How do I append or concatenate the first value (description) into the dropdown menu after the number? For example,
[ 1 ] descriptionInput (the value)
Everything works I just don't know how to pass the jQuery function back to JS or append each value.

How to delete a specific value in a cookie - jquery

I am developing a shopping cart system, where the user can add or remove products to his or her basket.
I am storing 2 things for each product in the product cookie: product barcode and price.
My code so far looks like this:
var addToBasketHandler = $(".add-product");
var removeFromBasketHandler = $(".unselect");
var Basket = {
select: function (box, cookie) {
box.addClass("selected");
var ean = box.attr('ean');
var value = box.find($(".price strong")).html().replace(/[^0-9\.]/g, '');
if ($.cookie(cookie) == undefined) {
$.cookie(cookie, ean + "~" + value);
} else if ($.cookie(cookie).indexOf(ean) == -1) {
$.cookie(cookie, $.cookie(cookie) + "|" + ean + "~" + value);
}
},
deselect: function (box, cookie) {
box.removeClass("selected");
// code to delete the cookie value
}
};
$(document).ready(function () {
$(addToBasketHandler).click(function () {
var box = $(this).parents(".box-offer");
Basket.select(box, "productCookie");
});
$(removeFromBasketHandler).click(function () {
var box = $(this).parents(".box-offer");
Basket.deselect(box, "productCookie");
});
});
And after adding 3 products to my cart, my cookie looks like this:
productCookie = 9918430821007~12.00 | 7C9918430831006~3.00 | 7C7501031311309~50.30
Please help on how I could remove only the selected product from this cookie list above.
FYI I am using jquery + jquery cookie
Try
deselect: function (box, cookie) {
box.removeClass("selected");
var ean = box.attr('ean');
var value = box.find($(".price strong")).html().replace(/[^0-9\.]/g, '');
var val = ean + "~" + value; //value to be removed
if ($.cookie(cookie) !== undefined) {
var cookie_val = $.cookie(cookie);
if (cookie_val.indexOf(val) !== -1) { //check value present in cookie
var arr = cookie_val.replace(' ', '').split('|'); //remove spaces and split with |
var index = arr.indexOf(val);//get index of value to be deleted
arr.splice(index, 1); //remove value from array
$.cookie(cookie, arr.join(' | ')); //convert array to sting using join and set value to cookie
}
}
}

Categories