I was trying to find a way to remove a letter (A,B,C) when I click three times on a button, I tried to use delete, because I don't want to use splice, because splice will change the order of the array. I want the variables letterA, letterB and letterC to keep their position on the array. What I was looking for was something like: if (randomletters == undefined) do math.random again, until it gets something different to undefined, maybe using a while.
I tried, but it doesn't seem to work. Do you have any solution for my problem? Please don't use jQuery, just normal JS.
var A = 0;
var B = 0;
var C = 0;
function incrementA() { A++; }
function incrementB() { B++; }
function incrementC() { C++; }
var letters = new Array()
letters[0] = 'letterA'
letters[1] = 'letterB'
letters[2] = 'letterC'
var randomletter;
function random() {
if (A == 3) { delete letters[0]; }
if (B == 3) { delete letters[1]; }
if (C == 3) { delete letters[2]; }
if ((A == 0 || A == 3) && (B == 0 || B == 3) && (C == 0 || C == 3)) {
randomletter = Math.floor(Math.random() * (letters.length));
if (randomletter == undefined) {
do {
randomletter = Math.floor(Math.random() * (letters.length));
} while(randomletter != undefined)
}
document.getElementById('text').innerHTML = letters[randomletter];
}
}
#green {
height: 20px;
width: 20px;
background: green;
}
#text {
height: 200px;
width: 200px;
background: yellow;
}
<div id="text" onclick="random()"> </div>
<button id="green" onclick="incrementA()">A </button>
<button id="green" onclick="incrementB()">B </button>
<button id="green" onclick="incrementC()">C </button>
You implemented the wrong comparison operator, and need to check the element, not the index.
your random() function should be something like:
function random() {
if (A == 3) { delete letters[0]; }
if (B == 3) { delete letters[1]; }
if (C == 3) { delete letters[2]; }
if ((A == 0 || A == 3) && (B == 0 || B == 3) && (C == 0 || C == 3)) {
do {
randomletter = Math.floor(Math.random() * (letters.length));
} while (letters[randomletter] == undefined)
document.getElementById('text').innerHTML = letters[randomletter];
}
}
The do-while ensures that randomletter is set once, then keeps setting it if the chosen value is undefined. You might want to add a check for "at least one element is valid" before the do-while begins or you could have an infinite loop scenario.
For example:
if (A > 2 && B > 2 && C > 2) {
// all elements of letters are undefined
} else if ((A == 0 || A == 3) && (B == 0 || B == 3) && (C == 0 || C == 3)) {
// do-while loop, because at least one element is valid
}
Related
I started studying Javascript about two weeks ago and I'm already trying to do some stuff for my company's website.
We have a wordpress elementor website, in which I created a new registration form, using javascript and Jquery to validate some specific fields, like CPF(like a SS number for brazilians), zip code and password.
All of these validation scripts are working fine, but just one of them (CPF), when I submit the form it sends without any value in this specific field.
Hope you guys can help me.
I used the following script to validate data of this field:
<input type="text" class="elementor-field elementor-size-lg elementor-field-textual" name="form-fields[field_cpf]" id="field_cpf" placeholder="Digite apenas números." maxlength="11" minlength="11" onblur="alertarFuncao()" required="required" aria-required="true">
<script>
//validation script
function verificaCPF(strCpf) {
var soma;
var resto;
soma = 0;
if (strCpf == "00000000000" ||
strCpf == "11111111111" ||
strCpf == "22222222222" ||
strCpf == "33333333333" ||
strCpf == "44444444444" ||
strCpf == "55555555555" ||
strCpf == "66666666666" ||
strCpf == "77777777777" ||
strCpf == "88888888888" ||
strCpf == "99999999999") {
return false;
}
for (i = 1; i <= 9; i++) {
soma = soma + parseInt(strCpf.substring(i - 1, i)) * (11 - i);
}
resto = soma % 11;
if (resto == 10 || resto == 11 || resto < 2) {
resto = 0;
} else {
resto = 11 - resto;
}
if (resto != parseInt(strCpf.substring(9, 10))) {
return false;
}
soma = 0;
for (i = 1; i <= 10; i++) {
soma = soma + parseInt(strCpf.substring(i - 1, i)) * (12 - i);
}
resto = soma % 11;
if (resto == 10 || resto == 11 || resto < 2) {
resto = 0;
} else {
resto = 11 - resto;
}
if (resto != parseInt(strCpf.substring(10, 11))) {
return false;
}
return true;
}
//function if the field validation script returns false
function campoInvalido(fieldId) {
fieldId.style.borderColor = "red"
}
//function if the field validation script returns true
function campoValido(fieldId) {
fieldId.style.borderColor = "green"
}
//function that runs when the user clicks/taps out off the field
function alertarFuncao() {
var strCpf = document.getElementById('field_cpf').value;
verificaCPF(strCpf);
if (!verificaCPF(strCpf)) {
campoInvalido(document.getElementById('field_cpf'))
alert('Por favor, insira um CPF válido.');
} else {
campoValido(document.getElementById('field_cpf'));
return document.getElementById('field_cpf').value = strCpf
}
}
</script>```
I tested your code snipet on my own web server, and once I found an input which passes your checks it seems to work.
I see however that you didn't include a element in your snippet. The input must be a child of one of these elements in order to send data. If you have a closing tag directly above this input field you should probably move it under.
I solved the problem turning the HTML custom field of elementor form into a regular text field, and did some modifications on the script, inserting an event listener to it. As I understood this is an Elementor form "problem", it doesn't recognize values in custom HTML fieds when submitting.
Here's the modified code:
var soma;
var resto;
soma = 0;
if (strCpf == "00000000000" ||
strCpf == "11111111111" ||
strCpf == "22222222222" ||
strCpf == "33333333333" ||
strCpf == "44444444444" ||
strCpf == "55555555555" ||
strCpf == "66666666666" ||
strCpf == "77777777777" ||
strCpf == "88888888888" ||
strCpf == "99999999999") {
return false;
}
for (i = 1; i <= 9; i++) {
soma = soma + parseInt(strCpf.substring(i - 1, i)) * (11 - i);
}
resto = soma % 11;
if (resto == 10 || resto == 11 || resto < 2) {
resto = 0;
} else {
resto = 11 - resto;
}
if (resto != parseInt(strCpf.substring(9, 10))) {
return false;
}
soma = 0;
for (i = 1; i <= 10; i++) {
soma = soma + parseInt(strCpf.substring(i - 1, i)) * (12 - i);
}
resto = soma % 11;
if (resto == 10 || resto == 11 || resto < 2) {
resto = 0;
} else {
resto = 11 - resto;
}
if (resto != parseInt(strCpf.substring(10, 11))) {
return false;
}
return true;
}
function campoInvalido(fieldId) {
fieldId.style.borderColor = "red"
}
function campoValido(fieldId) {
fieldId.style.borderColor = "green"
}
function alertarFuncao() {
var strCpf = document.getElementById('form-field-field_cpf').value;
verificaCPF(strCpf);
if (!verificaCPF(strCpf)) {
campoInvalido(document.getElementById('form-field-field_cpf'))
alert('Por favor, insira um CPF válido.');
} else {
campoValido(document.getElementById('form-field-field_cpf'));
return document.getElementById('form-field-field_cpf').value = strCpf
}
}
document.getElementById('form-field-field_cpf').addEventListener("blur", alertarFuncao);```
I am during writing game. When condition (playerlife < 1) is meet, game should stop. Whole game is in singlePlayer function. The problem is, I don't know how to end this function. Simple placing condition inside singlePlayer function doesn't work because it is checked only once during starting a game.
if (playerlife < 1) {
return;
}
I also tried to put this condition in interval and check if condition is meet continously but I doesn't work and anyway it doesn't looks like a good idea.
Below is part of code where after moving player there are checked some conditions. Game is similar to old school "Frogger". When player jump in to the water then he lost 1 life. After loosing 3 lives game should be over.
$(function() {
function singlePlayer() {
checkPosition(x, y) {
for (var i = 0; i < raftsTab.length; i++) {
if (x == raftsTab[i].PosX && y == raftsTab[i].PosY) {
let thisRaft = raftsTab[i];
console.log(x, y);
console.log(thisRaft);
clearInterval(MoveToPlayer);
movePlayer(thisRaft);
return;
}
}
for (var i = 0; i < raftsTab.length; i++) {
if (x !== raftsTab[i].PosX && y !== raftsTab[i].PosY && y !== 0 && y !== 5 && y !== 10) {
player1.lifes = player1.lifes - 1;
//player dead after loosing 3 lives - it would be perfect if game could be ended from here
$('.lifes').text("Player lifes: " + player1.lifes);
for (var i = 0; i < trophiesTab.length; i++) {
if (player1.trophie - 1 == i) {
trophiesTab[i].show();
player1.trophie = -1;
}
}
player1.PosX = 5;
player1.PosY = 10;
clearInterval(MoveToPlayer);
changePosition();
return;
}
}
for (var i = 0; i < trophiesTab.length; i++) {
if (x == trophiesTab[i].PosX && y == trophiesTab[i].PosY && player1.trophie == -1) {
trophiesTab[i].hide();
}
}
if (x == 5 && y == 0 && player1.trophie !== -1) {
tresure1 = tresure1 + player1.trophie;
player1.items = player1.items + 1;
$('.items').text("Gathered items: " + player1.items + "/3");
player1.trophie = -1;
console.log(tresure1);
}
clearInterval(MoveToPlayer);
}
}
});
I have a function that has to act different if pan.cost > 0.
So let's say curPos = 3 and pan.cost = -1
Now when I do this, no matter what, if(curPos + 1 === 5 || 30) is always used even if curPos + 1 is 2,3,4,6 etc (as long pan.cost < 0)
Now I have put console.log(curPos + 1) inside the else if-statement and it also says their that it does not meet the requirements.
function action(curPos)
{
var pan = panel[curPos];
if(pan.cost > 0)
{
}
else if(curPos + 1 === 5 || 39)
{
console.log(curPos + 1);
}
else if(curPos + 1 === 3)
{
console.log("should be here");
}
}
Try this:
function action(curPos)
{
var pan = panel[curPos];
var newCurPos = (curPost + 1);
if(pan.cost > 0)
{
}
else if(newCurPos === 5 || newCurPos === 39)
{
console.log(newCurPos);
}
else if(newCurPos === 3)
{
console.log("should be here");
}
}
The line
curPos + 1 === 5 || 39
always evaluates to truthy, because it is read:
(curPos + 1 === 5) || 39
and 39 is a truthy value.
if(curPos + 1 === 5 || 39) will always evaluate to true. Look at the part after your or pipes. if(39) will always be true.
|| 39 will always return true and pan.cost doesn't exist.
I want to generate 15 random numbers in the range 1-18 and assign them values. Here is my code. The problem is, when I press the button, the text displayed by Javascript, is 15 random items from the list I gave, which is exactly what I want, however, these items replace the 'Scramble' button. I want the button to stay so that I can generate another random list without reloading the page.
<!DOCTYPE html>
<html>
<head>
<title>text/javascript</title>
<script language="javascript">
function myFunction() {
document.getElementById('Scramble');
for (var i = 0; i < 15; i++) {
var x = Math.floor((Math.random()*18)+1)
if (x === 1) {
document.write("R ")
};
if (x === 2) {
document.write("R' ")
};
if (x === 3) {
document.write("R2 ")
};
if (x === 4) {
document.write("L ")
};
if (x === 5) {
document.write("L' ")
};
if (x === 6) {
document.write("L2 ")
};
if (x === 7) {
document.write("F ")
};
if (x === 8) {
document.write("F' ")
};
if (x === 9) {
document.write("F2 ")
};
if (x === 10) {
document.write("B ")
};
if (x === 11) {
document.write("B' ")
};
if (x === 12) {
document.write("B2 ")
};
if (x === 13) {
document.write("U ")
};
if (x === 14) {
document.write("U' ")
};
if (x === 15) {
document.write("U2 ")
};
if (x === 16) {
document.write("D ")
};
if (x === 17) {
document.write("D' ")
};
if (x === 18) {
document.write("D2 ")
};
};
};
</script>
</head>
<body>
<button onclick="myFunction()">Scramble</button>
<p id="Scramble"></p>
</body>
</html>
replace all the document.write(); with document.getElementById('Scramble').innerHTML= "string you want to display";
as you can see here
If you use document.write, you'll write directly in the document so you'll erase the previous data.
If you want to write in the #Scramble element, you use innerHtml :
var Scramble = document.getElementById('Scramble');
Scramble.innerHtml = 'new content';
I'm trying to loop my if statements inside a while loop through my function. But it will only hit the first if statement and stop looping.
Sample:
while(No.length == 0 || Name.length == 0 || Tel.length == 0
|| Date.length == 0 || Email.length == 0) {
alert("Don't leave blank!");
if (No.length == 0) {
document.getElementById('Nos').style.visibility = 'visible';
return false;
}
if(Name.length == 0) {
document.getElementById('Name').style.visibility = 'visible';
return false;
}
//continues same if statement for rest of the elements variables.
}
It will only go to the first if statement and will not loop through it.
You are returning from inside the loop; that breaks the loop. If you want to continue on to the next round of the loop, use continue instead. If you want to break out of the loop, but not return from the entire function, use break.
Now if you are using a jQuery loop, because it's really just a function, you do use return:
$.each([1,2,3,4], function(index, x) {
if (x < 4) return true; // equivalent to continue
if (x == 4) return false; // equivalent to break
});
but that's only for jQuery loops, not Javascript standard ones.
The first error I can see is you should escape your alert with '\' for example :
alert('Don\'t leave blank!');
And the loop with just continue if you write this :
while(No.length == 0 || Name.length == 0 || Tel.length == 0 || Date.length == 0 || Email.length == 0) {
if (No.length == 0) {
document.getElementById('Nos').style.visibility = 'visible';
}
if(Name.length == 0) {
document.getElementById('Name').style.visibility = 'visible';
}
return true;
}
Could also try:
while(No.length == 0 && Name.length == 0 && Tel.length == 0 && Date.length == 0 && Email.length == 0) {
document.getElementById('Nos').style.visibility = 'visible';
document.getElementById('Name').style.visibility = 'visible';
continue;
}
Maybe this?
function test_all_fields() {
var No = document.getElementById('No');
var Nos = document.getElementById('Nos');
var Name = document.getElementById('Name');
// ...
Nos.style.visibility = (No.value.length==0) ? 'visible':'hidden';
Names.style.visibility = (Name.value.length==0) ? 'visible':'hidden';
//...
//continues same if statement for rest of the elements variables.
if (No.value.length >0 && Name.value.length >0 && Tel.value.length>0 && Date.value.length >0 && Email.value.length>0) {
return true;
}
else {
alert("Don\'t leave blank!");
return false;
}
}