Javascript seemingly existing object - javascript

Unfortunately I can't easily paste the whole script that generates the variable, but I don't see it would be relevant either. Please instruct for more details, if necessary.
Javascript shows this:
console.log(gl.boxes);
shows:
[{element:{0:{jQuery19104057279333682955:9}, context:{jQuery19104057279333682955:9}, length:1}, boxName:"testi1", boxX:1, boxY:"180"}]
so gl.boxes[0] should exist, right? Still...
console.log(gl.boxes[0])
shows: undefined.
So what can I be missing here?
EDIT:
I will paste some more code about the generation of gl.boxes. Should be mostly about creating the variable as array first:
gl.boxes = [];
Then there is a function that handles creating and pushing new objects:
this.addBox = function (box) {
var retBox = {};
retBox.element = $(document.createElement('div'));
retBox.boxName = box.boxName;
retBox.boxX = box.boxX ? box.boxX : rootParent.defaultX;
retBox.boxY = box.boxY ? box.boxY : rootParent.defaultY;
retBox.element
.html(retBox.boxName)
.addClass(rootParent.boxClass)
.offset({ left: retBox.boxX, top: retBox.boxY })
.draggable({
stop: gl.URLs.dragStopDiv(retBox)
});
retBox.element.appendTo(rootParent.containerDiv);
gl.boxes.push(retBox);
return retBox;
};
The objects are created based on URL. Ie. in this test I have inline JS:
gl.objects.addBox({"boxName":"testi1","boxX":"50","boxY":"180"});
Only other place where the gl.boxes is being used is generating a URL based on the objects:
for(key in gl.boxes) {
var position = gl.boxes[key].element.position();
uri +=
"boxName["+key+"]="+gl.boxes[key].boxName+"&"+
"boxX["+key+"]="+position.left+"&"+
"boxY["+key+"]="+position.top+"&";
}

Maybe you need to change your loop to use indexes:
var i = 0,
position = {};
for (i = 0; i < gl.box.length; i += 1) {
position = gl.boxes[i].element.position();
uri += "boxName[" + i + "]=" + gl.boxes[i].boxName + "&" + "boxX[" + i + "]=" + position.left + "&" + "boxY[" + i + "]=" + position.top + "&";
}

Related

Current Alternative To .fontcolor() method in Javascript

I was given this task with some existing code to change the string color of each of three selector.value(s) that is output onto an input element to three different colors. The code boils the three selectors into a single output variable. Without destroying the code, I cannot figure out how to select each individual variables prior to condensing them.
If I could use the fontcolor() method, my life would be great but it's 2018 and I can't. Is there any way you can think of to solve this issue?To clarify, I need to alter the colors of the strings that belong to output(red), select1.value(blue) and select2.value(black.
Most of the action for this is happening in the parseOutput() function but I'm just stuck and don't think it's possible without rewriting the entire program.
function updateSelector(result){
var options = result.options;
var elementId = "select" + result.element;
var logger = document.getElementById('logger');
var selector = document.getElementById(elementId);
//logger.innerHTML = JSON.stringify(elementId);
selector.innerHTML = options;
selector.disabled = false;
}
google.script.run.withSuccessHandler(updateSelector).processOptions(0);
plate();
function resetAll(){
for (var i = 0;i<3;i++){
var selector = document.getElementById('select' + i);
selector.disabled = true;
selector.innerHTML = "";
}
google.script.run.withSuccessHandler(updateSelector).processOptions(0);
}
function finalSelection(){
var output = document.getElementById('out');
//output.focus();
output.select();
}
function plate(){
var plate = document.getElementById('plate');
plate.innerHTML = atob('Q3JhZnRlZCBieTogWmFjaGFyeSBTdGFjaG93aWFr');
}
//Adds the location as initial output, followed by divider, application, and issue if select1 is selected
//else statement added so if select0 is [Costco Website Name], to ommit the " - "
function parseOutput(){
var output = "";
if (select1.value.length > 0 && select0.value !== "[Costco Website Name]"){
output = output + ' - ' + select1.value + ' // ' + select2.value;
} else{
output = output + select1.value + ' // ' + select2.value;
}
out.value=output.trim();
}
And this is the Div that displays the output:
<div class="wide"><p><input class="wide" type="readonly" id="out" onfocus="this.select();"></p></div>
A modern replacement for fontcolor would use a span and a style (or class), e.g.:
function modernFontColor(str, color) {
return '<span style="color: ' + color + '">' + str + '</span>';
}
or
function modernFontClass(str, cls) {
return '<span class="' + cls + '">' + str + '</span>';
}
...where the class defines the styling.

I need my code to get the values before the commas but it only grabs one of them - Javascript

I am fairly new to the Javascript language.
I am trying to make a clicker game (not so hard). The game is working but I am trying to make a save method for the game.
Instead of cookies I decided to have the game make its own code where the user can copy and paste it the next time they get on the game.
So the save method works but when I try to have the game load the code it doesn't quite do it right.
Instead of grabbing the values before the commas it grabs the letters of the word I use as a checker.
Is there a way I can fix this?
Here's my code:
var shovel = 0;
var miner = 0;
var loaders = 0;
var drill = 0;
var tnt = 0;
var minecart = 0;
var bulldozer = 0;
var trucks = 0;
var manager = 0;
var cost1 = 10;
var cost2 = 200;
var cost3 = 350;
var cost4 = 500;
var cost5 = 600;
var cost6 = 800;
var cost7 = 2500;
var cost8 = 6000;
var cost9 = 100000;
var cash = 0;
var cashRate = 1000;
//-- SAVE GAME --
function save() {
var save = "";
var data = cash + "," + cashRate + "," + shovel + "," + miner + "," + loaders + "," + drill + "," + tnt + "," + minecart + "," + bulldozer + "," + trucks + "," + manager + "," + cost1 + "," + cost2 + "," + cost3 + "," + cost4 + "," + cost5 + "," + cost6 + "," + cost7 + "," + cost8 + "," + cost9;
save += "CoalMinerGame=" + data;
var finalSave = encode(save);//Encoding/Decoding is done using the Base64 Code
prompt("Keep this somewhere you'll remember!", finalSave);
}
function load() {
var code = prompt("Paste the save code below!", "");
if (code != "") {
var load = decode(code);
if (load.includes("CoalMinerGame=")) {
load.split("CoalMinerGame=");
//load[0] = blank
cash = load[1];
cashRate = load[2];
shovel = load[3];
miner = load[4];
loaders = load[5];
drill = load[6];
tnt = load[7];
minecart = load[8];
bulldozer = load[9];
trucks = load[10];
manager = load[11];
cost1 = load[12];
cost2 = load[13];
cost3 = load[14];
cost4 = load[15];
cost5 = load[16];
cost6 = load[17];
cost7 = load[18];
cost8 = load[19];
cost9 = load[20];
updateWorkers();
alert("Save Successfully Loaded!");
} else {
alert("Not a valid save code!");
}
} else {
alert("You must enter a save code to get your game back!");
}
}
Save
Load
I see two mistakes :
The load.split() function does not modify load but returns an array instead, an array that you should store in another variable.
You should also split once again the resulting string on commas to separate your different values.
Hope it helps!
Oh man, this code is giving me a pain :).
What about use some native functions for whole objects so you dont have to manually serialize it and deserialize it?
This code
const myObject = {
some: 'fields',
even: {
nested: 'fields',
},
};
const stringified = JSON.stringify(myObject);
console.log(stringified);
const unstringified = JSON.parse(stringified);
console.log(unstringified);
Is having this output
{"some":"fields","even":{"nested":"fields"}}
{ some: 'fields', even: { nested: 'fields' } }
You can also use base64 steps to code and decode
The JSON.stringify take JS object and create pure string which contains JSON inside.
Then when you want to take JSON and create object from it, you can just JSON.Parse, which expects string.
I echo the sentiment to use JSON. My example below might require some refactoring in the game code but would be cleaner. To access the variable cash you would just use gameData.cash where you currently are using the cash var.
var gameData = {
cash: 0,
cashRate:0,
shovel:0,
miner:0,
loaders:0,
drill:0,
tnt:0,
minecart:0,
bulldozer:0,
trucks:0,
manager:0,
cost1:10,
cost2:200,
cost3:350,
cost4:500,
cost5:600,
cost6:800,
cost7:2500,
cost8:6000,
cost9:100000
}
function save(){
var dataToSave = CoalMinerGame: {
cash: cash,
cashRate:cashRate,
shovel:shovel,
miner:miner,
loaders:loaders,
drill:drill,
tnt:tnt,
minecart:minecart,
bulldozer:bulldozer,
trucks:trucks,
manager:manager,
cost1:cost1,
cost2:cost2,
cost3:cost3,
cost4:cost4,
cost5:cost5,
cost6:cost6,
cost7:cost7,
cost8:cost8,
cost9:cost9
}
var finalSave = JSON.Stringify(dataToSave)
finalSave = encode(finalSave)
prompt("Keep this somwhere you'll remember!", finalSave)
}
function load(){
var code = prompt("Paste the save code below!", "")
var load = decode(code)
if (code != ""){
gameData = load;
updateWorkers();
alert("Save Successfully loaded!")
} else {
alert("You must enter a save code to get your game back!")
}
}

Javascript loop skipping iterations

I am working in a javascript function that takes all of the id's from a HTML table and sends each iteration of a loop and sends the info to a PLSQL procedure to update. I concat a number on each id to make each one unique. If I add an alert in the loop and click through one by one it works. If I let it go on its own with no alert it skips some iterations. Is there something that I am doing wrong?
function process_update() {
var nDataCount = document.getElementById("v_nDataCount").value;
var p_cc_no = document.getElementById("p_cc_no").value;
var p_orient = document.getElementById("p_orient").value;
var p_ot = document.getElementById("p_ot").value;
var p_buy = document.getElementById("p_buy").value;
var x = 0;
if (nDataCount == 0) {
x = 0;
} else {
x = 1;
}
for (i = nDataCount; i >= x; i--) {
var p_pc_no = ("p_pc_no[" + i + "]");
var p_pc_no2 = document.getElementById(p_pc_no).value;
var p_tm_name = ("p_tm_name[" + i + "]");
var p_tm_name2 = document.getElementById(p_tm_name).value;
var p_tm_no = ("p_tm_no[" + i + "]");
var p_tm_no2 = document.getElementById("p_tm_no").value;
var p_status = ("p_status[" + i + "]");
var p_status2 = document.getElementById(p_status).value;
var p_hrs_per_week = ("p_hrs_per_week[" + i + "]");
var p_hrs_per_week2 = document.getElementById(p_hrs_per_week).value;
var p_shift = ("p_shift[" + i + "]");
var p_shift2 = document.getElementById(p_shift).value;
var p_open = ("p_open[" + i + "]");
var p_open2 = document.getElementById(p_open).value;
var p_vacant = ("p_vacant[" + i + "]");
var p_vacant2 = document.getElementById(p_vacant).value;
var p_comments = ("p_comments[" + i + "]");
var p_comments2 = document.getElementById(p_comments).value;
var p_delete = ("p_delete[" + i + "]");
var p_delete2 = document.getElementById(p_delete).value;
window.location.href = "https://server.server.com/db/schema.package.p_process2?p_cc_no=" + p_cc_no + "&p_pc_no=" + p_pc_no2 + "&p_tm_name=" + p_tm_name2 + "&p_tm_no=" + p_tm_no2 + "&p_status=" + p_status2 + "&p_hrs_per_week=" + p_hrs_per_week2 + "&p_shift=" + p_shift2 + "&p_open=" + p_open2 + "&p_vacant=" + p_vacant2 + "&p_comments=" + p_comments2 + "&p_delete=" + p_delete2 + "&p_orient=" + p_orient + "&p_ot=" + p_ot + "&p_buy=" + p_buy + "";
}
Try the below code. I am using an AJAX GET request within the loop with request params, so as to not change the interface as much as possible. It uses only plain JS since I am not sure if you have jquery.
The actual changes start from line 48. Of course, I could test this code only in a limited way, so it might have possible bugs (please let me know). Also this can be possibly refined further, but as a quick fix it should do.
A word of caution: This could make a lot of calls in quick succession. So if you have too many loop iterations you might end up bringing down the server. Use wisely! :-) There should be some kind of batching to avoid this, but that will need the call interface to be changed.
Lines 48-61: I am creating a plain JS object out of all your parameters. The key is parameter name, value is the value to be passed.
Line 63: Here I am defining a self-invoking function, which makes the AJAX call in its body. This way, even though AJAX is asynchronous in nature, it will run in sync with the for loop outside.
Line 64-66: I am serializing the object created in the loop, into query parameters.
Lines 68,69: Framing the URL to which request will be made.
Lines 71-77: Actually making the request. This is just boilerplate AJAX-invoking code you can find anywhere (jQuery would've made life so much simpler :-)).
function process_update(){
var nDataCount = document.getElementById("v_nDataCount").value;
var p_cc_no = document.getElementById("p_cc_no").value;
var p_orient = document.getElementById("p_orient").value;
var p_ot = document.getElementById("p_ot").value;
var p_buy = document.getElementById("p_buy").value;
var x = 0;
if (nDataCount == 0) {
x = 0;
} else {
x = 1;
}
for (i = nDataCount; i >= x; i--) {
var p_pc_no = ("p_pc_no[" + i + "]");
var p_pc_no2 = document.getElementById(p_pc_no).value;
var p_tm_name = ("p_tm_name[" + i + "]");
var p_tm_name2 = document.getElementById(p_tm_name).value;
var p_tm_no = ("p_tm_no[" + i + "]");
var p_tm_no2 = document.getElementById("p_tm_no").value;
var p_status = ("p_status[" + i + "]");
var p_status2 = document.getElementById(p_status).value;
var p_hrs_per_week = ("p_hrs_per_week[" + i + "]");
var p_hrs_per_week2 = document.getElementById(p_hrs_per_week).value;
var p_shift = ("p_shift[" + i + "]");
var p_shift2 = document.getElementById(p_shift).value;
var p_open = ("p_open[" + i + "]");
var p_open2 = document.getElementById(p_open).value;
var p_vacant = ("p_vacant[" + i + "]");
var p_vacant2 = document.getElementById(p_vacant).value;
var p_comments = ("p_comments[" + i + "]");
var p_comments2 = document.getElementById(p_comments).value;
var p_delete = ("p_delete[" + i + "]");
var p_delete2 = document.getElementById(p_delete).value;
var dataObj = {p_cc_no:p_cc_no,
p_pc_no:p_pc_no2,
p_tm_name:p_tm_name2,
p_tm_no:p_tm_no2,
p_status:p_status2,
p_hrs_per_week:p_hrs_per_week2,
p_shift:p_shift2,
p_open:p_open2,
p_vacant:p_vacant2,
p_comments:p_comments2,
p_delete:p_delete2,
p_orient:p_orient,
p_ot:p_ot,
p_buy:p_buy};
(function(paramsObj){
var paramsStr = Object.keys(paramsObj).map(function(key) {
return key + '=' + paramsObj[key];
}).join('&');
var url = "https://server.server.com/db/schema.package.p_process2?";
url += paramsStr;
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('GET', url);
xhr.onreadystatechange = function() {
if (xhr.readyState>3 && xhr.status==200) {/*Handle Call Success*/};
};
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.send();
})(dataObj);
}
}

Function Scope issue when declaring an array of objects

This is the code that I currently have, one problem that is happening is I cannot use test() because presets[index].name and value are not visible outside of their function scope, how should I declare my array of objects in the global scope in order for me to be able to access these two variables in other functions?
var presets = [];
var index;
function CreatePresetArray(AMib, AVar) {
var parentpresetStringOID = snmp.getOID(AMib, AVar);
var presetStringOID = parentpresetStringOID;
parentpresetStringOID = parentpresetStringOID.substring(0, parentpresetStringOID.length - 2);
log.error("parentpresetStringOID is " + parentpresetStringOID);
var presetswitches = {};
for (var i = 1; i < 41; i++) {
presets.push(presetswitches);
try {
log.error("presetStringOID before getNextVB= " + presetStringOID);
vb = snmp.getNextVB(presetStringOID);
presetStringOID = vb.oid;
log.error("presetStringOID after getnextVB= " + presetStringOID);
var presetStringVal = snmp.get(presetStringOID);
log.error("presetStringVal= " + presetStringVal);
index = i - 1;
presets[index].name = presetStringOID;
presets[index].value = presetStringVal;
log.error("preset array's OID at position [" + index + "] is" + presets[index].name + " and the value stored is " + presets[index].value);
//log.error("presets Array value ["+index+"] = "+presets[index].configs);
if (presetStringOID.indexOf(parentpresetStringOID) != 0) {
break;
}
} catch (ie) {
log.error("couldn't load preset array " + index);
};
};
}
CreatePresetArray(presetMib, "presetString");
function test() {
for (i = 1; i < 41; i++) {
log.error("test" + presets[index].name + " " + presets[index].value);
};
}
test();
The for loop in your function test iterates over i but uses index inside the loop. Perhaps you meant to use
for (i = 0; i < 40; i++) { // 1 lower as you were using `index = i - 1` before
log.error("test" + presets[i].name + " " + presets[i].value);
}
Re-wrote your code. I don't think I made that much by way of change. If this doesn't clear up your problem, consider: Is the catch happening each iteration? Is the problem actually coming from a different method which is only visible here? Also, consider logging the whole presets Array when debugging to see what it looks like.
var presets = [];
function CreatePresetArray(AMib, AVar) {
var parentPresetOID, presetOID, presetValue, preset, vb, i;
parentPresetOID = snmp.getOID(AMib, AVar);
presetOID = parentPresetOID; // initial
parentPresetOID = parentPresetOID.substring(0, parentPresetOID.length - 2);
log.error("parentPresetOID is " + parentPresetOID);
presets = []; // empty array in case not already empty
for (i = 0; i < 40; ++i) {
try {
preset = {}; // new object
// new presetOID
vb = snmp.getNextVB(presetOID);
presetOID = vb.oid;
log.error("presetOID after getnextVB= " + presetOID);
// new value
presetValue = snmp.get(presetOID);
log.error("presetValue= " + presetValue);
// append data to object
preset.name = presetOID;
preset.value = presetValue;
// append object to array
presets.push(preset);
// more logging
log.error(
"preset array's OID at position [" + i + "]" +
" is" + presets[i].name + " and " +
"the value stored is " + presets[i].value
);
if (presetOID.indexOf(parentPresetOID) !== 0) {
break;
}
} catch (ie) {
log.error("couldn't load preset array " + i);
if (presets.length !== i + 1) { // enter dummy for failed item
presets.push(null);
}
}
}
}
Two options come to mind immediately:
you could pass the preset array as a argument to test().
You could put both CreatePresetArray() and test() inside a wrapper function and declare preset array at the top of your wrapper. That would give them both access to the variable.
It's generally considered Bad Form to declare globals if it can be avoided. Pollutes the namespace.

Is it possible to use cloneNode to clone multiple divs?

I'm trying to clone to divs in and append them to to other divs (their parents). I'm using clonenode for this but it doesn't seem to work. It clones the div in the first function and appends it to the parent of the div in the second function! Not sure what I'm doing wrong.
Here's the code (*EDIT:*var added):
function cloneQ() {
//Cloning questions and shit
cloneQ.id = (cloneQ.id || 0) + 1;
var question = document.getElementById("question");
var clone = question.cloneNode(true);
var numberOfQuestions = $('.question').length;
var id = "questioncon" + cloneQ.id;
clone.id = id;
question.parentNode.appendChild(clone);
var inid = "question" + cloneQ.id;
var optionid = "optionsdiv" + cloneQ.id;
$('#' + id + ' ' + '.' + 'questionin').attr('id', inid);
$('#' + id + ' ' + '.' + 'options').attr('id', optionid);
$('#' + id + ' h2').html('Question ' + cloneQ.id);
//Question Cloned
}
function cloneforPrint() {
cloneforPrint.id = (cloneforPrint.id || 0) + 1;
var questionprint = document.getElementById("questionprint");
var cloneprint = questionprint.cloneNode(true);
var printid = "questionprint" + cloneforPrint.id;
cloneprint.id = printid;
questionprint.parentNode.appendChild(clone);
var printinid = "thequestionprint" + cloneforPrint.id;
$('#' + printid + ' ' + '.' + 'thequestionprint').attr('id', printinid);
}
LIVE here: http://bit.ly/R8hB2m
Edit : Global vars are the problem.
You aren't putting var in front of your variables, making them global. The cloneForPrint function is picking up vars defined in cloneQ.
Init all the variables properly and you'll get some errors indicating where the problems are.
CloneQ is indeed appending to questions parent, but cloneForPrint then moves it somewhere else.
-- Old answer --
There's not enough here to work out what the problem is. My 1st guess is that the question element has the same parent as the questionprint element.
Based on the code given, cloneQ should definitely append to questions parent. So to give the appearance you've specified the DOM probably doesn't look like what you expect.

Categories

Resources