Javascript beginner question: Bool or Int? - javascript

I'm a Javascript beginner and I want to ask why a thing is happening in my code
var whoisplaying = 2;
function laX(lid) {
if (whoisplaying == 2) {
document.getElementById(lid).textContent = "X";
minus();
} else {
prompt("hi");
plus();
}
}
function minus() {
whoisplaying = 1;
}
function plus() {
whoisplaying = 2;
}
On this one above I have no issues on the on click function applied to a few buttons, while if I set the var whosiplaying as a bool as im gonna show in the next snippet, it doesnt work: the else statment will never be working, the var will always be true.
var whoisplaying = true;
function laX(lid) {
if (whoisplaying == true) {
document.getElementById(lid).textContent = "X";
minus();
} else {
prompt("hi");
plus();
}
}
function minus() {
whoisplaying = false;
}
function plus() {
whoisplaying = true;
}
Can someone explain me why, so I'll not make mistakes in the future? Thanks you.

Here are the two examples of yours, they behave the same way!, note that if(whoisplaying == true) could just be if(whoisplaying) when you check against booleans
Using Numbers
var whoisplaying = 2;
function laX() {
if(whoisplaying == 2) {
document.getElementById("lid").textContent="X";
minus();
}else {
prompt("hi");
plus();
}
}
function minus() {
whoisplaying = 1;
}
function plus() {
whoisplaying = 2;
}
<p id="lid"></p>
<button onclick="laX()">Click me</button>
Using Booleans
var whoisplaying = true;
function laX() {
if(whoisplaying == true) {
document.getElementById("lid").textContent="X";
minus();
}else {
prompt("hi");
plus();
}
}
function minus() {
whoisplaying = false;
}
function plus() {
whoisplaying = true;
}
<p id="lid"></p>
<button onclick="laX()">Click me</button>
Ok since you have added a comment that says
Don't ask me why but using boolenas it wasn't working when I tried it before... the else statement wasn't working...now it works both way.
I realised that the mistake was a typo in your code, I think you have typed = instead of == in your if statement although the given code doesn't have that typo, so that makes the if statement assign the true value each time to that variable and the returned value from that expression is truthy so the else never executes, but always the body of the if statement executes, here is an example
<p id="lid"></p>
<button onclick="laX()">Click me</button>
Using Booleans
var whoisplaying = true;
function laX() {
if(whoisplaying = true) {
document.getElementById("lid").textContent="X";
minus();
}else {
prompt("hi");
plus();
}
}
function minus() {
whoisplaying = false;
}
function plus() {
whoisplaying = true;
}
<p id="lid"></p>
<button onclick="laX()">Click me</button>

Related

function won't run the second part of the code how do I fix this?

Here is my code
function CheckForm_1() {
var F1 = document.getElementById('srch');
var Lgth = document.getElementById('srch');
if (F1.value == "") {
document.getElementById("Empty_Err");
Empty_Err.style.display = 'inline';
Empty_Err.stylebackgroundColor = 'linen';
return false;
} else {
return true;
}
if (Lgth.value.length > 17 || Lgth.value.length < 4) {
document.getElementById("Length_Err");
Length_Err.style.display = 'inline';
backgroundColor = 'linen';
alert("Search length must be be between 4 and 17");
return false;
} else {
return true;
}
}
I can't get it to check the field length Any ideas on this?
The code will run a check for an empty field just fine.
Returning value will stop execution of a function.
As #Calvin Nunes commented
When you use return, you stop the function execution because you
returned a value, so the function is terminated...that's why you'll
never reach the second if, because in the first if you return or true
or false
function CheckForm_1() {
var F1 = document.getElementById('srch');
var errorMessage = document.getElementById("errorMessage");
if (F1.value == "") {
errorMessage.style.display = 'inline';
errorMessage.style.backgroundColor = 'linen';
errorMessage.innerHTML= "Search field is empty";
} else if (F1.value.length > 17 || F1.value.length < 4) {
errorMessage.style.display = 'inline';
errorMessage.style.backgroundColor = 'linen';
errorMessage.innerHTML = 'Search length must be be between 4 and 17';
} else {
errorMessage.style.display = 'none';
}
}
<input id='srch' type="text" />
<div id="errorMessage" style="display:none">Search field is empty</div><br>
<button type="button" onclick="CheckForm_1()">Submit</button>

Validation. Checking and calling a function

I want to call a function only when the form is valid. Validation works correctly, but I can not correctly call the addUser () function. The test worked, but it's looped, the next time it's called, the test is done twice, the next 5 times. There can be several telephones.
// code
if (lastName.value.match(letters)) {
for(var i = 0; i < phones.length; i++){
if (!phones[i].value.match(digts)) {
//checking
if(phones[phones.length - 1].value != '') {
addUser();
};
error.innerHTML = 'Only digits';
frm.insertBefore(error, phones[i]);
break;
}
}
} else {
if(user.value == ''){
//code
}
errorMessage = "false";
}
if (errorMessage !== "") {
event.preventDefault();
}
}
----------
function addUser(){
$('#registration').submit(function(event) {
alert(12);
//code
event.preventDefault();
var data = 'phones=' + JSON.stringify(arrUserInfo);
$.ajax({
//code
});
});
}
You can add validations in another function and return true or false depending on validation result,and call that function on form submit.
function validations()
{
....
for(var i = 0; i < phones.length; i++){
if (!phones[i].value.match(digts)) {
// set error message
return false;
}
}
if(user.value == ''){
// set error message
return false;
}
return true;
}
$('#registration').submit(function(event) {
if(validations())
{
$.ajax({
// code
});
}
else
{
return false;
}
});

How to query multiple conditions or results of anonymous functions in jQuery

First of all, I have a form with several input fields and some Bootstrap-Buttons. Now, what I want to do is to check, if two conditions ("Are all input fields filled?" ; "Is at least one Button pushed down?") are fullfilled to enable the user to click the submit button.
This is my code:
function checkInput() {
var inputFields = $("input[name=inp1],[name=inp2],[name=inp3]");
var buttons = $("button[name=btn1],[name=btn2],[name=btn3]");
var empty1;
var empty2;
buttons.click(function() {
if(!$(this).hasClass('active')) {
empty1 = false;
} else {
empty1 = true;
}
});
inputFields.keyup(function() {
inputFields.each(function() {
if($(this).val().length == 0) {
empty2 = true;
} else {
empty2 = false;
}
});
});
alert(empty1);
alert(empty2);
if(empty1 == true && empty2 == true) {
$('button[name=submitBtn]').prop('disabled', false);
} else {
$('button[name=submitBtn]').prop('disabled', true);
}
}
The alert(...) functions say, that empty1 and empty2 are "undifined", which i can understand. But my question is, how can I retrieve the true or false values from buttons.click() and inputFields.keyup() to query them afterwards?
The problem is the scope of the variables, those vars need to be global:
var empty1;
var empty2;
function checkInput() {
var inputFields = $("input[name=inp1],[name=inp2],[name=inp3]");
var buttons = $("button[name=btn1],[name=btn2],[name=btn3]");
buttons.click(function () {
if (!$(this).hasClass('active')) {
empty1 = false;
} else {
empty1 = true;
}
});
inputFields.keyup(function () {
inputFields.each(function () {
if ($(this).val().length == 0) {
empty2 = true;
} else {
empty2 = false;
}
});
});
alert(empty1);
alert(empty2);
if (empty1 == true && empty2 == true) {
$('button[name=submitBtn]').prop('disabled', false);
} else {
$('button[name=submitBtn]').prop('disabled', true);
}
}
Move it outside of the function an it will works:
see it in jsFiddle working example

How can i stop my animation circle ? - JS

i'm doing a game with javascript only using function, i know it's not the best method but i'm still learning prototypes before steping in to use them. So, to the point, i have a request animatation frame that calls him self so my function keep executing. The problem is when the player dies i want to stop the enemys to be created , basicaly, stop the functions execution. Better show you some code.
This is my animation function:
function animate() {
if (endGame() == true) {
return;
}
requestAnimationFrame(animate);
if(theBird == null && canContinue == true) {
theBird = getBird(); // variavel com a div do bird
setTimeout(createDrake(), Math.round(Math.random() * 800));
setTimeout(createBrick(), Math.round(Math.random() * 3000));
setTimeout(createBoss(), Math.round(1000 + Math.random() * 15000));
setTimeout(createPowerUp(), Math.round(Math.random() * 15000));
document.addEventListener('keydown', onKeyPressed);
document.addEventListener('keyup', onKeyReleased);
}
else {
updateBirdLocation();
updateBirdSpeed();
flyDrakes();
flyBrick();
flyBullets();
flyPowerUp();
flyBoss();
checkBulletCollisions();
checkBulletCollisionsBricks()
checkShipCollision();
checkShipCollisionBricks();
checkShipCollisionBonusP();
checkShipCollisionBoss();
checkBulletCollisionsBoss();
updateScores();
checkEnemyBulletCollisions();
MoveArrayX(bullets2, -10);
MoveArrayX(bullets3, -10);
removePassingElements();
}
}
And this one is my function stopGame that is beeing called everytime player looses:
function endGame() {
Rbutton.style.visibility= "visible";
var RestartDiv = document.createElement("div");
RestartDiv.id = "RestartDiv";
gameDiv.appendChild(RestartDiv);
document.getElementById('RestartDiv').innerHTML += "You scored" + " " + mobHits + " " + "points!";
canContinue = false;
return true;
}
My attemp to stop this was the 1st part of animate :
function animate() {
if (endGame() == true) {
return;
}
but if i do this my game stops ( like i want ) but before the player dies.
I do not have endGame beeing executed anywhere besides the functions where the player dies. How can i solve this ?
Thank you
EDIT: This is an example how i detect a player died:
function checkShipCollisionBoss() {
for (var k=0; k<bossArray.length; k++) {
if ((isCollide(BirdsDiv, bossArray[k]) ) == true){
endGame();
}
}
}
isCollide is a function that detects the collision.
Then do like this,
function endGame() {
if(isCollide()) // return a boolean from this function
{
Rbutton.style.visibility= "visible";
var RestartDiv = document.createElement("div");
RestartDiv.id = "RestartDiv";
gameDiv.appendChild(RestartDiv);
document.getElementById('RestartDiv').innerHTML += "You scored" + " " + mobHits + " " + "points!";
canContinue = false;
return true;
}
return false;
}
Also remember this, if you are going to check a boolean you can simple give
if(true) or if (false)
Example,
var bool = true;
if(bool)
// your stuff
Your endGame function always return true, so endGame() == true
Then in animate function:
function animate() {
if (endGame() == true) {
return;
}
...
}
which is:
function animate() {
if (true == true) {
return;
}
...
}
which is:
function animate() {
if (true) {
return;
}
...
}
which is:
function animate() {
return;
...
}
So it always return

JS loop only works when matching to the last element in an array

I cannot get the loop to work in my simple js login script. When i try to login with any login other than the last one in the array (user3 and pass3) it returns false.
What am I doing wrong?
I have tried both == and ===.
var userLogins = [{user:"user1", password:"pass1"},{user:"user2", password:"pass2"},{user:"user3", password:"pass3"}]
var success = null;
function logon(user, pass) {
userok = false;
for (i = 0; i < userLogins.length; i++)
{
if(pass == userLogins[i].password && user == userLogins[i].user )
{
success = true;
}
else
{
success = false;
}
}
secret(success);
}
function getData() {
var user = document.getElementById("userid").value;
var password = document.getElementById("password").value;
logon(user, password);
}
function secret(auth){
if(auth)
{
show('success');
hide('login');
}
else
{
show('error');
hide('login');
}
}
function show(show) {
document.getElementById(show).className = "show";
}
function hide(hide) {
document.getElementById(hide).className = "hide";
}
for (i = 0; i < userLogins.length; i++)
{
if(pass == userLogins[i].password && user == userLogins[i].user )
{
success = true;
}
else
{
success = false;
}
}
You need a break in there, otherwise your true value for success simply gets overwritten with false on the next iteration... except for the last possible credentials, for which there is no "next" iteration.
Once you've done that, you don't actually need the else branch at all:
var success = false;
for (i = 0; i < userLogins.length; i++) {
if (pass == userLogins[i].password && user == userLogins[i].user) {
success = true;
break;
}
}
Use break when you found it. Otherwise the next loop will set success to false.
for (var i = 0; i < userLogins.length; i++)
{
if(pass == userLogins[i].password && user == userLogins[i].user )
{
success = true;
break;
}
else
{
success = false;
}
}
secret(success);

Categories

Resources