Javascript if clause won't work - javascript

I'm having trouble with a javascript function that needs to take a global variable into account.
It's kind of a control mechanism I would like to implement, but I can't seem to get it right.
Here's the relevant code
<script type="text/javascript">
var active = 0;
function SetEndTime(lngOpenPersonID,lngToDoID){
if(active = 0){
alert('Time has been stopped');
}
else{
var strURL = 'blabla';
CallAJAXURL(strURL);
}
active = 0;
}
function SetStartTime(lngToDoID,lngToDoItemID,bitCountsForTotal){
if(active = 1){
alert('Time has been started');
}
else{
var strURL = 'blabla';
CallAJAXURL(strURL);
}
active = 1;
}
When I call SetStartTime without doing anything else, I always get the alert. Is there something wrong with my syntax?

if (active == 0) {
You need 2 "=" characters to make a comparison operator. There's also === which performs an equality comparison without type promotion.
Your code is syntactically correct because an assignment operation is a valid expression. The first if statement you had:
if (active = 0) {
will never be true, because the value of the expression is always zero. The second one:
if (active = 1) {
conversely is always true because the value is always one.

its not (alert = 1) .. its ( alert == 1 ).. your condition says its always true -- your assigning alert to 1

Related

How to nest an if-statement inside a function? - Javascript

Now that I have a recursive function, I wonder what is best in order for the same flow to continue.
Nest an another function, isn't it?
In other words, I would like another prompt that asks the user's age when the user answers yes to the first prompt.
The issue that I'm facing now is that the last prompt does not comeback if the user writes something different than "yes" or "no".
They way I've nested it makes the prompts pop up in a way that I can't figure out:
function showPrompt(msg) {
var str = prompt(msg).toLowerCase();
if (str === "yes") {
function showPrompt(firstQuestion) {
var age = prompt(firstQuestion).toLowerCase();
if (age < 21) {
alert("You're too young. Go home.");
} else if (age >= 21) {
alert("Welcome.");
} else {
showPrompt(firstQuestion);
}
}
showPrompt("How old are you?");
} else if (str === "no") {
alert("goodbye.");
} else {
showPrompt(msg);
}
}
showPrompt("Do you like gambling?");
The problem is that you are overwriting your function. If you give your second function another name I guess it works the way you want. And as given in the other answer, you do not need to define your function in the condotional clause:
function showPrompt(msg) {
var str = prompt(msg).toLowerCase();
if (str === "yes") {
nextQuestion("How old are you?");
} else if (str === "no") {
alert("goodbye.");
} else {
showPrompt(msg);
}
}
function nextQuestion(secondQuestion) {
var age = parseInt(prompt(secondQuestion));
if (typeof age == "number" && age < 21) {
alert("You're too young. Go home.");
} else if (typeof age == "number" && age >= 21) {
alert("Welcome.");
} else {
showPrompt(secondQuestion);
}
}
showPrompt("Do you like gambling?");
Your problem is the conditional creation of showPrompt within the function called showPrompt, see Function declarations inside if/else statements?. While such declarations are allowed, they have side effects and should be avoided.
One side effect is that the conditional function declaration creates a local variable that is undefined unless execution enters the if block and assigns it a value. In the OP, the local showPrompt declaration shadows the global showPrompt created by the global function declaration. Hence if the block is not entered, when it's called, its value is undefined and a TypeError is thrown, e.g.
// Global foo
var foo = 23;
function bar() {
// Declaration creates a local foo even if
// if block is not entered
if (false) {
function foo (){}
}
// foo is undefined
console.log(typeof foo);
}
bar();
To fix that, change the name of the function in the if block and move it out of the block.
Also, as pointed out by epascarello, you should do numeric comparisons using numbers, not strings. When using comparison operators, if one of the values is a number, then the other will be converted to number too for the comparison. But if they are both strings (prompt returns a string), they'll be compared as strings. But for readability, it's best to use numbers for both sides.
Finally, you should test the value returned by the prompt to see it's a string. If the user clicks "Cancel", it will return null and calling toLowerCase will throw an error. So if the value isn't a string, the user clicked cancel and the function should handle it (e.g. exit).
function showPrompt(msg) {
function showPrompt2(firstQuestion) {
var age = prompt(firstQuestion);
if (typeof age != 'string') {
return;
}
if (+age < 21) {
alert("You're too young. Go home.");
} else if (+age >= 21) {
alert("Welcome.");
} else {
showPrompt2(firstQuestion);
}
}
var str = prompt(msg);
if (typeof str != 'string') {
return;
}
str = str.toLowerCase();
if (str === "yes") {
showPrompt2("How old are you?");
} else if (str === "no") {
alert("goodbye.");
} else {
showPrompt(msg);
}
}
showPrompt("Do you like gambling?")

javascript if state function doesn't read boolean

My code work with resize function boolean change with width,
but my function contain if statement doesn't read the boolean,
what is problem with my code?
I used = ==, but I don't know how to use them exactly
var footerMenu = ['#about', '#help']
var slideSwitch = false
function slideDown(){
footerMenu.forEach(function(list){
$(list+' p').click(function(){
$(list+' ul').slideToggle(300)
})
})
}
function slideClear(){
for( let i = 0; i < footerMenu.length; i++){
$(footerMenu[i]+' p').click(function(){
var choice = footerMenu[i]
footerMenu.splice(i, 1);
footerMenu.forEach(function(list){
$(list+' ul').slideUp(300)
})
footerMenu.splice(i, 0, choice);
})
}
}
function slideTotal(){
if(slideSwitch = true){
slideDown()
slideClear()
}
}
$(document).ready(function() {
checkWidth();
});
$(window).resize(function(){
checkWidth();
});
function checkWidth(){
$vWidth = $(window).width();
if($vWidth <576){
console.log("Width: Less than 576");
slideSwitch = true
}else{
console.log("Width: More than 576");
slideSwitch = false
}
}
slideTotal()
I hope correct my code, if I don't have any wrong please advice me how to solve it
= is the assignment operator. It changes the value of what is on the left hand side. It is usually not what you want in an if statement unless you really know what you are doing.
== and === are the comparison operators. The different between them is that == automatically converts the two arguments to the same type, whereas === does not. But that doesn't really matter, my advice is to always use === to compare variables in an if statement.
Also, comparing to true (x === true) is completely pointless because that is what an if statement already does; it is unnecessary.
(side note: you could do if (x === true === true === true), and that would be the same as if (x).)
The code you want is:
function slideTotal() {
if (slideSwitch) {
slideDown();
slideClear();
}
}
Well, to start:
function slideTotal(){
if(slideSwitch = true){
slideDown()
slideClear()
}
}
change: slideSwitch = true
to: slideSwitch == true

Difference between looping in the code when I try to loop and stop a function:

When I try to run the cycleimagesfunc() in javascript console, the first section of my code works, but then it doesn't work in the second section. I'm trying to keep track of each key press so that a key press will trigger the function to run and display the next image.
<p id="demo8">first</p>
function cycleimagesfunc(){
if(document.getElementById("demo8").innerHTML==="first"){
document.getElementById("demo8").innerHTML ="third";
console.log("0");
return;
}
if(document.getElementById("demo8").innerHTML==="third"){
document.getElementById("demo8").innerHTML ="fourth";
console.log("1");
return;
}
if(document.getElementById("demo8").innerHTML==="fourth"){
document.getElementById("demo8").innerHTML ="fifth";
console.log("2");
return;
}
var cyclecount = 0;
function cycleimagesfunc(){
if(cyclecount = 0){
console.log("0");
cyclecount++;
return;
}
if(cyclecount = 1){
console.log("1");
cyclecount++;
return;
}
if(cyclecount = 2){
console.log("2");
cyclecount++;
return;
}
}
The problem is with your use of assignment operator (=) instead of the comparison operator (==) or (===) in your conditionals. This assigns the cyclecount to the value instead of checking against it. Note that use of a triple equals sign also guards against 'truthy' values by additionally checking the type.
You also shouldn't be running return in your function, as this will prevent any further function logic happening after the condition is met. You're presumably wanting to do something after the cyclecount increases!
The conditionals are fixed, and the returns are removed in the follow example:
var cyclecount = 0;
function cycleimagesfunc() {
if (cyclecount === 0) {
console.log("0");
cyclecount++;
}
if (cyclecount === 1) {
console.log("1");
cyclecount++;
}
if (cyclecount === 2) {
console.log("2");
cyclecount++;
}
}
cycleimagesfunc();
Hope this helps! :)

If statement not executing correct code?

So I am trying to develop a Tic Tac Toe game for practice with javascript but I've hit a roadblock. I have an if statement that should be returning true but it isn't. Here is a sample.
var game = true;
var x = 'X';
var o = 'O';
var blank = '';
var turn = x;
var board = [blank, blank, blank,
blank, blank, blank,
blank, blank, blank];
function write() {
$('td').click(function() {
//Making sure that the block that was clicked can only be clicked once
var id = $(event.target).attr('id');
var digit = parseInt(id.slice(-1));
//check to see of the block has been clicked on
if (board[digit] = blank) {
board[digit] = turn;
$(board[digit]).html(turn.toUpperCase());
if (turn = x) {
turn = o;
} else if (turn = o) {
turn = x;
}
} else {
alert("That box has already been clicked on!")
}
});
}
You have two issues at first glance.
First, event is undefined. Define it as a function parameter in your .click call.
$('td').click(function(event) { /* rest of the code */ }
Second, as Pointy commented, = is for assignment, == and === are meant for comparisons.
Thus
if (board[digit] = blank) { /**/ }
needs to be
if (board[digit] === blank) { /**/ }
Regarding the difference between == and === you can get more information here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness
Short version, prefer === unless you're absolutely sure you know what you're doing and want to explicitly use ==.
if (board[digit] === blank) {
^^

Javascript .click() different for elements w/ same class

I'm pretty new to Javascript/Jquery and am implementing a real simple image carousel for practice and ran into a problem regarding Jquery's "click" method.
The code I currently have is as follows:
$(document.getElementsByClassName("traverse")).click(function() {
if(this.id = "left"){
if (current == 0) {
current = images.length-1;
}
else {
current -= 1;
}
}
else if(this.id = "right") {
if(current = images.length-1) {
current = 0;
}
else {
current += 1;
}
}
$(document.getElementById("image-view")).css("background-image", "url(" + images[current] + ")");
});
With this code there are no errors, but every time I click either the "#right" or "#left" button, they both run code as if "this.id = 'left'". While I understand I can simply separate the two and this will work fine, is there a way I can do it similar to what I have now where I'm applying this event to the class, but differentiating the behavior by the id?
Thanks!
Typo
== to compare
= to assign
Strict equal (===) Returns true if the operands are equal and of the
same type
if(this.id === "left"){
^
and better use
class selector
$('.traverse').click(function(){ .. });
Problem with your code
you are assign this.id = "left" every time in if condition so is condition is always true
if(this.id = "left"){
You're setting this.id to left by only using a single = sign. Try this:
$(document.getElementsByClassName("traverse")).click(function(event) {
if(event.target.id === "left"){
and so on.

Categories

Resources