createElement creates infinite loop - javascript

I'm really new to javascript, and coding in general, and I can't understand why this causes an infinite loop:
let newTr = document.createElement('tr');
If I take it out, the webpage loads fine, but if I leave it in, the webpage never fully loads and my browser uses 50% of my CPU.
Here's the rest of my code:
// client-side js
// run by the browser each time your view template referencing it is loaded
console.log('hello world :o');
let arrPfcCases = [];
// define variables that reference elements on our page
const tablePfcCases = document.getElementById("tablePfcCases");
const formNewPfcCase = document.forms[0];
const caseTitle = formNewPfcCase.elements['caseTitle'];
const caseMOI = formNewPfcCase.elements['caseMOI'];
const caseInjuries = formNewPfcCase.elements['caseInjuries'];
// a helper function to call when our request for case is done
const getPfcCaseListener = function() {
// parse our response to convert to JSON
arrPfcCases = JSON.parse(this.responseText);
// iterate through every case and add it to our page
for (var i = 0; i = arrPfcCases.length-1;i++) {
appendNewCase(arrPfcCases[i]);
};
}
// request the dreams from our app's sqlite database
const pfcCaseRequest = new XMLHttpRequest();
pfcCaseRequest.onload = getPfcCaseListener;
pfcCaseRequest.open('get', '/getDreams');
pfcCaseRequest.send();
// a helper function that creates a list item for a given dream
const appendNewCase = function(pfcCase) {
if (pfcCase != null) {
tablePfcCases.insertRow();
let newTr = document.createElement('tr');
for (var i = 0; i = pfcCase.length - 1; i++) {
let newTd = document.createElement('td');
let newText = document.createTextNode(i.value);
console.log(i.value);
newTd.appendChild(newText);
newTr.appendChild(newTd);
}
tablePfcCases.appendChild(newTr);
}
}
// listen for the form to be submitted and add a new dream when it is
formNewPfcCase.onsubmit = function(event) {
// stop our form submission from refreshing the page
event.preventDefault();
let newPfcCase = [caseTitle, caseMOI, caseInjuries];
// get dream value and add it to the list
arrPfcCases.push(newPfcCase);
appendNewCase(newPfcCase);
// reset form
formNewPfcCase.reset;
};
Thanks!
P.S. There are probably a ton of other things wrong with the code, I just can't do anything else until I figure this out!

As an explanation, in your code
i = pfcCase.length - 1
assigned the value of pfcCase.length - 1 to i. The syntax of that part of the loop should be
an expression to be evaluated before each loop iteration. If this expression evaluates to true, statement is executed.
The evaluation of your code made no sense.
Evaluating
i < pfCase.length
before each iteration to check that the current index is less than the length of the array, however, works correctly.

Here is no conditional statement here. In this statement you are assigning pfcCase length minus 1 to the I variable.
for (var i = 0; i = pfcCase.length - 1; i++) {
You have to compare the i variable to the length of the pfcCase minus 1.
This should work.
for (var i = 0; i < pfcCase.length - 1; i++) {
noticed something else
This line does not do what you think it dose.
let newText = document.createTextNode(i.value);
i is just the index i.e. a number. It does not have the value property.
This is what you are looking to do.
let newText = document.createTextNode(pfcCase[i].value);
my preference (forEach)
I prefer using the array forEach method. It’s cleaner and less prone to mistakes.
pfcCase.forEach( function(val){
let newTd = document.createElement('td');
let newText = document.createTextNode(val.value);
console.log('The array element is. '. val.value, ' The value is. ', val.value);
newTd.appendChild(newText);
newTr.appendChild(newTd);
});

Related

Passing variables through addEventListener

I am trying to add event to all inputs, get the value (number) from those and insertHtml them into span elements.
This is my javascript code. I have no idea how to pass the variables.
var input_selector = document.querySelectorAll('.coins_n'); // input number elements
var price_selector = document.querySelectorAll('.price'); // span elements
for(var i = 0; i <= input_selector.length; i++) {
var input = input_selector[i];
var price = price_selector[i];
input.addEventListener('input', function(){
console.log(price); // not working
console.log(input); // not working
price.innerHTML = input.value; // not working
})
}
The problem here has to do with scoping of your variables. var is a weird one, whose scope isn't really limited to the block, but to the containing function. The following two are (essentially) the same:
var input;
var i = 0;
for(; i < input_selector.length; i++) input = input_selector[i];
and
for(var i = 0; i < input_selector.length; i++) var input = input_selector[i];
both create a variable named input in global scope, and then update that variable. That means that any functions that wants to read input later will just read the last version of input, and not the version at the time you defined the handler you would trigger later.
let, however, is block scoped, and your for loop is a block. So defining let input inside the for loop will mean that input is defined uniquely for every iteration of the loop, since every time the block gets executed a new scope is created for everything in there.
The same is true for var i = 0 in your for loop - any handler that calls it later will just log the last global value of i, but if you use let, that's not the case and every iteration of the loop has its own i. So your code could simply be reduced to this:
const input_selector = document.querySelectorAll('.coins_n');
const price_selector = document.querySelectorAll('.price');
for( let i = 0; i < input_selector.length; i++ ){
input_selector[i].addEventListener('input', event => {
price_selector[i].innerHTML = event.target.value;
});
}
This is pretty complex to explain once you start typing it out, so better read what other have already written at something like MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let
Ok. I've managed it by using let.
var input_selector = document.querySelectorAll('.coins_n');
var price_selector = document.querySelectorAll('.price');
for(var i = 0; i < input_selector.length; i++) {
let input = input_selector[i];
let price = price_selector[i];
input_selector[i].addEventListener('input', function(){
price.innerHTML = this.value;
})
}

Why is this JavaScript looping twice in Zapier?

Here is a video that shows what I'm struggling with.
Here is a high level description of the process, followed by the actual JavaScript code I've written.
PROCESS
I built 2 Zaps that each run like this:
STEP 1 - Trigger (Cognito Form, which has repeating sections)
STEP 2 - JavaScript Code (which creates an Array of the form fields for ONE of the repeating sections, and separates them into individual strings using .split)
STEP 3 - Action (creates a ZOHO CRM Task for each string)
The first Zap runs on one of the sections of the form (Visits with Sales), and the second zap runs on a different section of the form (Visits without Sales). Each of these Zaps works fine on their own so I know the code is good, but I want to combine the two Zaps into one by combining the code.
I tried to combine by making five steps:
Trigger - Code1 - Zoho1 - Code2 - Zoho2
but the Zoho2 Tasks were each repeated
I then tried to re-order the five steps:
Trigger - Code1 - Code2 - Zoho1 - Zoho2
but now Zoho1 Tasks AND Zoho2 tasks were duplicated.
Finally I tried to combine ALL the JavaScript code into one:
Tigger - CombinedCode1+2 - Zoho 1 - Zoho2
but only the strings from Arrays in "Code2" are available to me when I go to map them in Zoho1.
CODE:
if (inputData.stringVSAccount == null) {
var listVSAccountArray = [];
var listVSUnitsArray = [];
var listVSPriceArray = [];
var listVSNotesArray = [];
var listVSVisitCallArray = [];
} else {
var listVSAccountArray = inputData.stringVSAccount.split(",");
var listVSUnitsArray = inputData.stringVSUnits.split(",");
var listVSPriceArray = inputData.stringVSPrice.split(",");
var listVSNotesArray = inputData.stringVSNotes.split(",");
var listVSVisitCallArray = inputData.stringVSVisitCall.split(",");
}
var output = [];
var arrayNos = listVSAccountArray.length;
var i = 0;
do {
var thisItemVSAccount = new String(listVSAccountArray[i]);
var thisItemVSUnits = new String(listVSUnitsArray[i]);
var thisItemVSPrice = new String(listVSPriceArray[i]);
var thisItemVSNotes = new String(listVSNotesArray[i]);
var thisItemVSVisitCall = new String(listVSVisitCallArray[i]);
var thisItemObj = {};
thisItemObj.itemVSAccount = thisItemVSAccount;
thisItemObj.itemVSUnits = thisItemVSUnits;
thisItemObj.itemVSPrice = thisItemVSPrice;
thisItemObj.itemVSNotes = thisItemVSNotes;
thisItemObj.itemVSVisitCall = thisItemVSVisitCall;
output.push({ thisItemObj });
i++;
} while (i < arrayNos);
//This is where the second zaps code is pasted in the combined version
if (inputData.stringOVAccount == null) {
var listOVAccountArray = [];
var listOVNotesArray = [];
var listOVVisitCallArray = [];
} else {
var listOVAccountArray = inputData.stringOVAccount.split(",");
var listOVNotesArray = inputData.stringOVNotes.split(",");
var listOVVisitCallArray = inputData.stringOVVisitCall.split(",");
}
var output = [];
var arrayNos = listOVAccountArray.length;
var i = 0;
do {
var thisItemOVAccount = new String(listOVAccountArray[i]);
var thisItemOVNotes = new String(listOVNotesArray[i]);
var thisItemOVVisitCall = new String(listOVVisitCallArray[i]);
var thisItemObj = {};
thisItemObj.itemOVAccount = thisItemOVAccount;
thisItemObj.itemOVNotes = thisItemOVNotes;
thisItemObj.itemOVVisitCall = thisItemOVVisitCall;
output.push({ thisItemObj });
i++;
} while (i < arrayNos);
I just started learning JavaScript this week, and sense that I am missing something obvious, perhaps a set of brackets. Thanks for any assistance
David here, from the Zapier Platform team. You're running into a confusing and largely undocumented feature where items after a code step run for each item returned. This is usually desired behavior - when you return 3 submissions you want to create 3 records.
In your case, it's also running subsequent unrelated actions multiple times, which sounds like it's undesired. In that case, it might be easier to have 2 zaps. Or, if "Zoho2" only ever happens once, put it first and let the branch happen downstream.
Separately, I've got some unsolicited javascript advice (since you mentioned you're a beginner). Check out Array.forEach (docs), which will let you iterate through arrays without having to manage as many variables (your own i every time). Also, try to use let and const over var when possible - it keeps your variables scoped as small as possible so you don't accidentally leak values into other areas.
​Let me know if you've got any other questions!
Just a note - you are declaring the same array variable output in both segments of your code block - the second declaration will be ignored.
Use the .forEach() method to iterate over your arrays, it will significantly cleanup you code. You also don't need to painstakingly construct the objects to be pushed into the output arrays.
This may not fix your issue but the code is far easier on the eye.
var listVSAccountArray = [],
listVSUnitsArray = [],
listVSPriceArray = [],
listVSNotesArray = [],
listVSVisitCallArray = [],
output = [];
if (typeof inputData.stringVSAccount === 'string') {
listVSAccountArray = inputData.stringVSAccount.split(',');
listVSUnitsArray = inputData.stringVSUnits.split(',');
listVSPriceArray = inputData.stringVSPrice.split(',');
listVSNotesArray = inputData.stringVSNotes.split(',');
listVSVisitCallArray = inputData.stringVSVisitCall.split(',');
}
// iterate over the array using forEach()
listVSAccountArray.forEach(function(elem, index){
// elem is listVSAccountArray[index]
output.push({
itemVSAccount: elem,
itemVSUnits: listVSUnitsArray[index],
itemVSPrice: listVSPriceArray[index],
itemVSNotes: listVSNotesArray[index],
itemVSVisitCall: listVSVisitCallArray[index]
})
})
//This is where the second zaps code is pasted in the combined version
var listOVAccountArray = [],
listOVNotesArray = [],
listOVVisitCallArray = [],
output_two = []; // changed the name of the second output array
if (typeof inputData.stringOVAccount === 'string') {
listOVAccountArray = inputData.stringOVAccount.split(',');
listOVNotesArray = inputData.stringOVNotes.split(',');
listOVVisitCallArray = inputData.stringOVVisitCall.split(',');
}
// iterate over the array using forEach()
listOVAccountArray.forEach(function(elem, index){
// elem is listOVAccountArray[index]
output_two.push({
itemOVAccount: elem,
itemOVNotes: listOVNotesArray[index],
itemOVVisitCall: listOVVisitCallArray[index]
});
});

JavaScript Search and Loop - doesn't return correct values

Please, can you check my code where is the error? It should loop trough 1 array to choose each string and then loop through second array and check, if the value from second string contains value of first string.
for (var i = 0; i < oldLines.length; i++){
var subStringEach = oldLines[i];
var subStringEachNoDash = subStringEach.replace(/[^a-z0-9]/g,'');
// read New URLs and line by line save them as an object
var newLines = $('#newUrl').val().split(/\n/);
var newUrlResult = [];
for (var j = 0; j < newLines.length; j++){
var newUrlString = newLines[j];
var newUrlStringNoDash = newUrlString.replace(/[^a-z0-9]/g,'');
var isThere = newUrlStringNoDash.search(subStringEachNoDash);
if (isThere !== -1 ) {
newUrlResult[i] = newLines[j];
}
else {
newUrlResult[i] = "";
}
}
stockData.push({OldURL:oldLines[i],SearchSubstring:subStringEach,NewURL:newUrlResult[i]});
}
Now it finds only part of the results.. I place to first array:
anica-apartment
casa-calamari-real
ostrovni-apartman
and to the second array:
http://tempweb3.datastack.cz/be-property/anica-apartment/
http://tempweb3.datastack.cz/be-property/ostrovni-apartman/
http://tempweb3.datastack.cz/be-property/st-michael-apartment/
http://tempweb3.datastack.cz/be-property/casa-calamari-real/
and it will only find and return casa-calamari-real, http://tempweb3.datastack.cz/be-property/casa-calamari-real/ and the others returns empty..
Any ideas please?
Here is the full code on Codepen: https://codepen.io/vlastapolach/pen/VWRRXX
Once you find a match you should exit the inner loop, otherwise the next iteration of that loop will clear again what you had matched.
Secondly, you should use push instead of accessing an index, as you don't know how many results you will have. And as a consequence you will need to relate the find string with it (because i will not be necessary the same in both arrays)
So replace:
if (isThere !== -1 ) {
newUrlResult[i] = newLines[j];
}
else {
newUrlResult[i] = "";
}
with this:
if (isThere !== -1 ) {
newUrlResult.push({
searchSubstring: subStringEach,
newURL: newUrlString
});
break; // exit loop
}
At the end, just output newUrlResult.
NB: If you want to leave the possibility that a search string matches with more than one URL, then you don't need the break. The push will then still prevent you from overwriting a previous result.
I see that you solved already) But maybe you will like this code too)
newUrlResult variable could be a string I guess, because loop breaks when one value is found. If no values where found there will be just empty string. And I'm not sure you need to call newLines = $('#newUrl').val().split(/\n/) on every iteration.
var stockData = [];
oldLines.map(function(oldLine){
var cleanOldLine = oldLine.replace(/[^a-z0-9]/g,''),
newLines = $('#newUrl').val().split(/\n/),
newUrlResult = '';
for (var j = 0; j < newLines.length; j++){
var newLine = newLines[j],
cleanNewLine = newLine.replace(/[^a-z0-9]/g,''),
ifExists = cleanNewLine.search(cleanOldLine);
if (ifExists !== -1) {
newUrlResult = newLine;
break;
}
}
stockData.push({OldURL:oldLine, SearchSubstring:cleanOldLine, NewURL:newUrlResult});
});

Javascript function to return page id's

I'm lookingfor a javascript function which returns the next value from an array on every function call.. I have created a script but i'm a little stuck now.. is there someone to help me?
My location:
resultLocation= "beugen";
This should be the identifier to get the correct array of id's. There will be more arrays with id''s for example resultLocation = "mill";
My array of Id's
var beugen = [];
beugen[0] = "140";
beugen[1] = "33";
beugen[2] = "121";
beugen[3] = "150";
beugen[4] = "52";
beugen[5] = "68";
beugen[6] = "70";
beugen[7] = "82";
beugen[8] = "15";
My function to return a value. (the next value should be shown on each call of getId (resultLoction)
getId = function(resultLocation) {
var arrayLength = beugen.length;
page = beugen;
for (var i = 0; i < arrayLength; i++) {
init_table(page[i]);
}
}
getId(resultLocation);
Now my function keeps on looping and calls the init_table(page[i]) as many times as there are id's in my array. It should get the first (140) on the first call of getId and the 2nd (33) on the next call, and if it reaches the end, it should start over again at the the top.
Maybe an array is not the best solution? I don't really know. Since there are multiple locations?
var i = -1;
function getId(){
i++;
if(i>beugen.length-1){
i=0;
}
init_table(beugen[i]);
return beugen[i];
}
or something like that might work if i understand the problem.

Add numbers from dynamic site with new page load

How do you write a function/ listener in javascript that can fire when html updates?
html page is limited to the last 100 records
html page continuously adds new records (nodes)
I need to...
push the values into an array or increment a variable to sum the values
display the running total in html
Trying to create a counter that adds new values to the sum.
I believe the code below only executes once.
window.onload = function() {
var data = document.getElementsByTagName('span');
var len = data.length;
var total = 0;
var searchValue = "value";
for (var i = 0; i < len; ++i) {
var styles = data[i].getAttribute('style');
if (styles == searchValue) {
var txt = data[i].innerHTML;
split = txt.split(" ");
total += parseInt(split[2]);
}
}
console.log(total);
};
Yes you can do this with just JavaScript, and a little HTML/CSS for displaying the number.
Note that it requires a fair deal of experience to manage an addon with cross-origin requests, and to show it to the user.

Categories

Resources