Does not execute the code after a for within a function - javascript

Good! I have a problem and you do not run my code at the end of the loop, the above and what is inside the loop works fine, the problem is that after the loop is still not executing the code. Any idea why it can be?
This is my code:
var arrayp = new Array();
function botonAdelante(tabl, pasos)
{
var padreTabla = document.getElementById(tabl).rows;
var cont = 0;
for(var j = 0; j < padreTabla.length; j++)
{
var hijoTd = document.getElementById(pasos+ "-producto-" +j);
var childArray = hijoTd.children;
for(var i = 0; i < childArray.length; i++)
{
var check = document.getElementById(pasos+ "-CheckBox-" +j);
if(check.type == 'checkbox' && check.checked==true)
{
arrayp[cont] = check.value;
var algo = arrayp[cont];
alert(arrayp[cont]);
alert(arrayp);
cont++;
continue;
};
}
}
alert("It is in this part of the code does not work");
}
Clarification: "continue" found at the end of long and if it will not work either.

The continue is confusing used like this, but I have a feeling your code is probably throwing an error because the cont might exceed the array length. Regardless of whether this fixes it or not I'd at least add a check to ensure that it doesn't throw an exception.
Please check for exceptions being thrown through web dev tools (F12 in Chrome).
for(var i = 0; i < childArray.length; i++)
{
var check = document.getElementById(pasos+ "-CheckBox-" +j);
if(check.type == 'checkbox' && check.checked==true && arrayp.length <= cont)
{
arrayp[cont] = check.value;
var algo = arrayp[cont];
alert(arrayp[cont]);
alert(arrayp);
cont++;
continue;
};
}

Related

Increment with remainder not working

In my script the computer clicks through contact tabs in WhatsApp Web and for each checks whether the person is online or not. This is done with a loop, which starts again when contact number 16 is reached. Anyhow, the loop doesn't work and the variable 'i' doesn't increase. This is strange, since if I replace selectContact(${i}) by console.log, the increment works. Maybe the ${} prevents the i from updating?
var i = 1
setInterval(function () {
selectContact(`${i}`)
if (document.getElementsByClassName("O90ur")[0] !== undefined) {
var online = document.getElementsByClassName("O90ur")[0].innerHTML
if (online == "online") {
console.log(`${i}`)};
}
i = i % 16 + 1
}, 1000);
Here is the code for selectContact, if the issue should lie within here.
var jq = document.createElement('script');
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);
contacts = [];
chat_div = [];
function triggerMouseEvent(node, eventType) {
var event = document.createEvent('MouseEvents');
event.initEvent(eventType, true, true);
node.dispatchEvent(event);
}
function getChatname(){
$("#pane-side > div > div > div").find("._2FBdJ > div._25Ooe").each(function(){
contacts.push($(this).text());
chat_div.push($(this));
})
}
function selectContact(name){
getChatname()
for (i = 0; i < contacts.length; i++){
if (name.toUpperCase() === contacts[i].toUpperCase()){
triggerMouseEvent(chat_div[i][0],"mousedown")
}
}
}
You've missed out the var statement declaring i in your for loop, meaning it overwrites your global i.
function selectContact(name){
getChatname()
for (var i = 0; i < contacts.length; i++){
if (name.toUpperCase() === contacts[i].toUpperCase()){
triggerMouseEvent(chat_div[i][0],"mousedown")
}
}
}

I have repeated JS code, how do I turns these into functions

Here is the JSFiddle link for my project, you can see the full app.js here... https://jsfiddle.net/be4pLh7s/1/
Basically I am trying to build a contact diary where you can create new contacts and then be able to edit or delete them at a later stage...
on line 85 onwards is the click event for the Edit and Delete buttons, I THINK that the way I have written this part of the code maybe incorrect because I have repeated loops and if statements.
I have tried putting these repeated parts of the code into functions but then the app crashes and I receive different errors. I have tried a couple of things to overcome these errors but still cant get it to work and or get my head around this.
Please could you advise if the code is correct... have I repeated myself? If I have then please can you show/tell me how to make this code better in terms of DRY, and readability. Thank you.
How do I code separate functions for the "Edit", "Save" and "Delete" buttons.
This line of code is repeated 3 times -
for (var i = 0; i < contactsBook.length; i++) {
if (contactsBook[i].firstName === ul.getAttribute('data-person')) {}
This line of code is repeated 2 times -
const ulChild = ul.childNodes;
for (var j = 0; j < ulChild.length; j++) {
if (ulChild[j].tagName === "LI") {}
Here is the part of the code in question -
//Click event for Edit and Delete buttons.
contacts.addEventListener("click", (e) => {
if (e.target.tagName === "BUTTON") {
const button = e.target;
const ul = button.parentNode;
if (button.textContent === "Edit") {
for (var i = 0; i < contactsBook.length; i++) {
if (contactsBook[i].firstName === ul.getAttribute('data-person')) {
const ulChild = ul.childNodes;
for (var j = 0; j < ulChild.length; j++) {
if (ulChild[j].tagName === "LI") {
const items = ulChild[j];
const input = document.createElement('input');
input.type = 'text';
input.value = items.textContent;
items.textContent = "";
items.insertBefore(input, ulChild.childNodes);
button.textContent = 'Save';
};
};
};
};
} else if (button.textContent === "Save") {
for (var i = 0; i < contactsBook.length; i++) {
if (contactsBook[i].firstName === ul.getAttribute('data-person')) {
const ulChild = ul.childNodes;
for (var j = 0; j < ulChild.length; j++) {
if (ulChild[j].tagName === "LI") {
console.log(ulChild[j]);
};
};
};
};
} else if (button.textContent === "Delete") {
contacts.removeChild(ul);
for (var i = 0; i < contactsBook.length; i++) {
if (contactsBook[i].firstName === ul.getAttribute('data-person')) {
contactsBook.splice(i,1);
localStorage.setItem('addbook', JSON.stringify(contactsBook));
};
};
};
};
});
Thank you for your help!
Not much of repeated code. Only hint I could give is if you want to use more javascrpt flare, e.g. .forEach instead of standard for loop and .filter since you have a for and if statement.
For an example
for (var i = 0; i < contactsBook.length; i++) {
if (contactsBook[i].firstName === ul.getAttribute('data-person'))
....
Can be done with:
contactsBook.filter(book => book.firstName === ul.getAttribute('data-person'))
Not that it makes any difference.

Regex doesn't return true in a loop

I wrote simple regex to check few words and then put them into an new array. Everything works fine, when I check values manually, but when I put it into loop, I receive false. My question is - why? I think there's something wrong in my if statement, but for me it's ok... Here's my code:
var elements = ["sztuka", "sztuki", "sztuk", "sztukateria", "sztukmistrz", "sztuczka"];
var correctElements = [];
var reg = /^sztuk[ia]$/ig;
function checkElements(reg, elements) {
for (var i=0; i < elements.length; i++) {
if (reg.test(elements[i] == true)) {
correctElements.push(elements[i]);
} else {
return false;
}
}
console.log(correctElements);
}
When I check it manualy I receive true:
var reg = /^sztuk[ia]$/ig;
console.log(reg.test(elements[0]));
I would be very grateful if you could help me with that and explain why it's happening.
reg.test(elements[i] == true) need to be reg.test(elements[i]) == true)
You shouldn't return false until you iterate through all the items. Check the following working snippet.
var elements = ["sztuka", "sztuki", "sztuk", "sztukateria", "sztukmistrz", "sztuczka"];
var correctElements = [];
var reg = /^sztuk[ia]$/ig;
checkElements(reg,elements);
function checkElements(reg, elements) {
console.log("hi");
for (var i=0; i < elements.length; i++) {
if (reg.test(elements[i]) == true) {
correctElements.push(elements[i]);
}
}
console.log(correctElements);
}

JavaScript loop through to check duplicate value

I am having troubles trying to check if the date exists in the array.
for(var i = 0; i< crisislist.length; i++){
hazecounter = 1;
if(crisislist[i].category == 1){
if(crisislist[i].date != crisislist[i+1].date) {
hazelabel.push(crisislist[i].date);
}else{
hazecounter++;
}
hazedata.push(hazecounter);
}
}
The sample data for the date is:
["01-02-2017", "22-03-2017", "22-03-2017", "07-08-2017"]
And the expected output for hazelabel, hazedata should be:
hazelabel: ["01-02-2017", "22-03-2017", "07-08-2017"]
hazedata: [1,2,1]
With the code above, when I check until the last element in the array and trying to make a comparison, it throw me an error message:
Uncaught TypeError: Cannot read property 'date' of undefined
I think this is because when I reach the last element of array, and I try to find crisislist[I+1].date, it could not found and thus the error message.
Any idea how to fix this? Thanks in advance!
You must access crisislist[i+1].date only when i doesn't point to the last element.
Also notice that to get the desired result, you need to move the hazedata.push inside the if block and put the initialisation of hazecounter in front of the loop.
var hazecounter = 1;
for (var i = 0; i< crisislist.length; i++) {
if (crisislist[i].category == 1) {
if (i == crisislist.length-1 || crisislist[i].date != crisislist[i+1].date) {
hazelabel.push(crisislist[i].date);
hazedata.push(hazecounter);
hazeCounter = 1;
} else {
hazecounter++;
}
}
}
Your if statement is going to be a problem.
if(crisislist[i].date != crisislist[i+1].date) {
You are accessing crisislist[i+1] in a loop that goes to < crisislist.length. That means that if you have an array of size 4, your loop will go until i = 3, but you are accessing i+1 from the array (crisislist[4]), which will be undefined.
Try changing your for loop to go to crisis.length-1
You just need to check till second last :
for(var i = 0; i< (crisislist.length-1); i++){
hazecounter = 1;
if(crisislist[i].category == 1){
if(crisislist[i].date != crisislist[i+1].date) {
hazelabel.push(crisislist[i].date);
if (crisislist.length-2 == i)
{
hazelabel.push(crisislist[i+1].date);
}
}else{
hazecounter++;
}
hazedata.push(hazecounter);
}
}
Check that code. If you have any questions, add a comment :) In my solution dates dont have to be sorted.
</head>
<BODY>
<script>
function Something(date)
{
this.date = date;
this.category = 1;
}
var crisislist = [];
var hazelabel = [];
var hazedata = [];
crisislist[0] = new Something("01-02-2017");
crisislist[1] = new Something("22-03-2017");
crisislist[2] = new Something("22-03-2017");
crisislist[3] = new Something("07-08-2017");
for(var i = 0; i< crisislist.length; i++){
if(crisislist[i].category == 1)
{
if(!hazelabel[crisislist[i].date])
{
hazelabel[crisislist[i].date] = crisislist[i].date;
hazedata[crisislist[i].date] = 1;
}
else
{
hazedata[crisislist[i].date]++;
}
}
}
for(var key in hazelabel)
{
console.log(hazelabel[key]);
console.log(hazedata[key]);
}
</script>
</BODY>
</HTML>

javascript for stopped working

This is how script appeared in Wordpress visual editor and database. Has been working fine until this pm.
if (xmlhttp.readyState==4) {
if ( xmlhttp.status==200)
{
document.getElementById("droptargethere").innerHTML=xmlhttp.responseText;
var svg = document.getElementById("droptargethere").childNodes;
for(var i = 0; i < svg.length; i++) {
var element = svg[i];
if (element.localName == "div") {
var rect = element.offsetTop;
var retID = element.id;
updTable (retID , rect , "../wp-admin/custom/");
}
}
}
but viewing source in browser looks like this, essentially corrupted. After the for statement it is one continuous line.
if (xmlhttp.readyState==4) {
if ( xmlhttp.status==200)
{
document.getElementById("droptargethere").innerHTML=xmlhttp.responseText;
var svg = document.getElementById("droptargethere").childNodes;
for(var i = 0; i < svg.length; i++) { var element = svg[i]; if (element.localName == "div") { var rect = element.offsetTop; var retID = element.id; updTable (retID , rect , "../wp-admin/custom/"); } } }
Further investigation showed it was the following line that seems to cause the issue
for(var i = 0; i < svg.length; i++)
Tried re-keying, while.., do...while but makes no difference.
Also appears not to like "if" statements. Frustrating
Anyone got any ideas, due to demonstrate to client in morning and I cannot see a way round it.
Thanks

Categories