Why won't a simple Javascript if condition execute? - javascript

<!DOCTYPE html>
<html>
<body>
<button onClick="Display()"></button>
<script>
function Display() {
var a = 0;
if(a = 0){
alert("hello world");
}
}
</script>
</body>
</html>
I run the page and clicked the button and nothing happens. I can't for the life of me figure out why...
Edit: on another note, THIS code executes no matter what, even if I haven't defined var CorrectActivities:
function Display() {
if(CorrectActivities = 3) {
document.getElementById("ActivitiesResult").innerHTML = '<span>style="color:DarkGreen;font-weight:bold;font-size:30px;">3 out of 3 correct!</span>';
} else if (CorrectActivities = 2) {
document.getElementById("ActivitiesResult").innerHTML = '<span style="color:Crimson;font-weight:bold;font-size:30px;">2 out of 3 correct!</span>';
} else if (CorrectActivities = 1) {
document.getElementById("ActivitiesResult").innerHTML = '<span style="color:Crimson;font-weight:bold;font-size:30px;">1 out of 3 correct!</span>';
} else {
document.getElementById("ActivitiesResult").innerHTML = '<span style="color:Crimson;font-weight:bold;font-size:30px;">0 out of 3 correct!</span>';
}
}
Edit2: thanks for the answers. First code is fixed, second is still broken regardless of what I try. Going to look for errors elsewhere in the script...

When you compare values, you should use == (equal) or === (equal and same type). = is only for setting variable value.
<!DOCTYPE html>
<html>
<body>
<button onClick="Display()"></button>
<script>
function Display() {
var a = 0;
if(a == 0){
alert("hello world");
}
}
</script>
</body>
</html>
To your another code, I created a jsfiddle. There you have same problem as in first part, wrong comparison operator. It didn't run if CorrectActivities wasn't declared. I fixed it (like in first part), declared variable and added three buttons to test all cases and it seems to work.
You also have small typo in case 3, you have an extra closing bracket at <span>style

a = 0 is assignment not a valid condition. a == 0, a === 0 or !a will all work for what you want.
Same is the case with CorrectActivities, use CorrectActivities == 3 instead of CorrectActivities = 3.

in javascript = assign a value and return it, == or === compare values
The first part wont execute because:
You click the button
Display get called
if(a = 0) evaluate to if(0) which is to javascript if(false)
so the code inside if won't run. what you want is if(a == 0):
function Display() {
var a = 0;
if (a == 0) {
alert("hello world");
}
}
<button onClick="Display()"></button>
for the second part if(CorrectActivities = 3) will be if(3) which is to javascript if(true) so it will always run. again what you want is using the == operator:
function Display () {
if ((CorrectActivities == 3)) {
document.getElementById('ActivitiesResult').innerHTML = '<span>style="color:DarkGreen;font-weight:bold;font-size:30px;">3 out of 3 correct!</span>'
} else if ((CorrectActivities == 2)) {
document.getElementById('ActivitiesResult').innerHTML = '<span style="color:Crimson;font-weight:bold;font-size:30px;">2 out of 3 correct!</span>'
} else if ((CorrectActivities == 1)) {
document.getElementById('ActivitiesResult').innerHTML = '<span style="color:Crimson;font-weight:bold;font-size:30px;">1 out of 3 correct!</span>'
} else {
document.getElementById('ActivitiesResult').innerHTML = '<span style="color:Crimson;font-weight:bold;font-size:30px;">0 out of 3 correct!</span>'
}
}

This is because instead of comparing,you are assigning it.
So the statement if(a = 0) always comes out to be true.
Use == instead of =.
function Display() {
var a = 0;
if(a = 0){
alert("hello world");
}
}
This will help.

Related

Returning the correct item from the array

I am using code.org and I am trying to return the item from the array but receiving an error on line 34 that possibleFoods[selectedFood] is undefined. I cannot understand why, and is this what is stopping the food selections block from working? How should I correctly define selectedFood?
setScreen("BaseScreen");
onEvent("selectionbutton", "click", function( ) {
setScreen("food_decision_screen");
});
var selections = [true, true, true];
var possibleFoods = [
{name:"Raw pasta prima vera", info:{recipe:"", prepTime:{total:20,cook:0, prep:20}, image:""}},
{name:"Zucchini chips", info:{recipe:"", prepTime:{total:55,cook:30, prep:25}, image:""}}
];
var possibleFoods;
onEvent("preference_finished_button", "click", function( ) {
selections = [
getChecked("radio_buttonhot"),
getChecked("radio_buttonvege"),
getChecked("radio_button0-30")
];
if (selections[0] == false) {
if (selections[1] == false) {
if (selections[2] == true) {
selectedFood = 1;
}
}
}
setText("t_textOutputFoodInfo", "total time: " +
possibleFoods[selectedFood].info.prepTime.total);
setText("t_textOutput_foodSelectedName", "name: " +
possibleFoods[selectedFood].name);
});
selectedFood is undefined. Unsure how to define.
The selectedFood variable is not declared. Moreover, you are assigning it inside nested if conditions which might not be true always.
Try this:
Declare selectedFood outside with an initial value, right before the if statements.
var selectedFood = 0;
You have few problems here:
selectedFood is not being declared- e.g it has no "const", "var" or "let" before it.
If you do not know about scopes and the difference between var, const and let- read a bit here. Then you'll understand why its best to define selectedFood before the if blocks, and only fill up the value inside, like this:
let selectedFood;
if (selections[0] == false) {
if (selections[1] == false) {
if (selections[2] == true) {
selectedFood = 1;
}
}
}
selectedFood is undefined simply because it's not declared, in addition this line is never reached in your case: selectedFood = 1;.
Depending on what you're trying to achieve, build your conditions using Logical Operators.
replace this:
if (selections[0] == false) {
if (selections[1] == false) {
if (selections[2] == true) {
selectedFood = 1;
}
}
}
With this:
let selectedFood = 0; // Set by default to 0
if (!selections[0] && !selections[1] && selections[2]) {
selectedFood = 1;
}
Hope this helps!
EDIT: I might be able to give a more straight forward answer if you could link me to the challenge you're trying to solve.

Cannot call a nested function

As the question says, I can't call a nested function!
Here's the JavaScript:
var n;
var i = 0;
$("#men").click(function(){
$("#reshead").slideToggle("300");
});
$("#nxt").click(function() {
pic(i+=n);
});
$(window).on("scroll", function() {
if($(window).scrollTop() > 50) {
$("#header").addClass("scroll");
} else {
$("#header").removeClass("scroll");
}
});
function pic(n) {
if(n=1){
dx1();
} else if (n==2) {
dx2();
} else if (n=3){
dx3();
} else{
n=0;
}
}
function dx1() {
document.getElementById("picb").style.backgroundImage='url("src/black-belt.png")';
}
function dx2() {
document.getElementById("picb").style.cssText+='background-image:url(src/kut.png);background-repeat:no-repeat; width:auto;height:auto;';
}
function dx3() {
document.getElementById("picb").style.cssText+='background-image:url(src/slmb.jpg);background-repeat:no-repeat; width:auto;height:auto;';
}
I tried everything possible. Nothing happens. The code is for a slideshow in which the background image alone changes.
I first tried it in jQuery but it didn't happen. So I tried in plain JavaScript and it still doesn't work.
if(n=1)
and
else if(n=3)
are assingments and not comparison operators...
You are assigning a value to n so it's always entering to the first if. Try using == operator:
function pic(n) {
if(n==1){
dx1();
}
else if(n==2){
dx2();
}
else if(n==3){
dx3();
}
else{
n=0;
}
}
Be aware that even with the syntax fixes, you will still run into a problem trying to add undefined to 0.
pic(i+=n);
where the first time it is called i equals 0 and n equals undefined. Afterwards, i will equal NaN and n will equal 0.

How to toggle between functions on button click

I have a button that I want to switch between 2 different functions when clicked. like first click would call function A, second click would call function B, Third Click would call function A etc.
for html I have something like this:
<input type="image"onclick="test()">
for javascript I have:
<script>
val = 1;
function test () {
if (val = 1 ) {
function1 ();
}
else {
function2 ();}
}
</script>
<script>
function function1() {
alert("1");
val = 2;}
</script>
<script>
function function2() {
alert("2");
val = 1;}
</script>
it only ever runs function1 Even if I set val = 2 it will run function1. any idea what im doing wrong?
You were using the assignment operator to check the value. Use the equality operator instead:
<script>
val = 1;
function test () {
if (val == 1 ) { // compare values using == (or maybe ===)
function1();
val = 2; // use the assignment operator here
}
else {
function2();
val = 1;
}
}
</script>
Update:
As #nnnnnn pointed out, you might want to update your toggle state inside test() directly.
If you need only toggle button, you can try XOR style function.
<script>
val = 0;
function toggle(){
val = val ^ 1; // XOR 0^1 => 1, 1^1 => 0
if(val == 0){
//do something
}else{
//do something else
}
}
</script>
OR in shorter way
<script>
val = 0;
function toggle(){
val = val ^ 1; // XOR 0^1 => 1, 1^1 => 0
val == 0 ? function1(): function2();
}
</script>

Changing Scope from Global to Local Breaking Javascript Program

Thanks to the help of you fine Overflowians, I fixed up my silly little RNG Addition game and got it working. Now, at one user's suggestion, I'm trying to change the scope of the addition game's code from global to local before I code up the next game; I want each game to be completely contained within its own scope, as I understand that learning to not thoughtlessly contaminate the global scope is a good idea. However, I'm a bit stuck on how to achieve that.
Here's the code for the currently functional addition game:
function beginAdditionChallenge() {
var x = Math.ceil(Math.random()*100);
alert(x);
for (var i = 0; i < 3; i++) {
var a = Number(prompt("Provide the first addend.", ""));
var b = Number(prompt("Provide the second addend.", ""));
if (a + b === x) {
alert("Well done!");
break;
}
else if (a + b !== x && i < 2) {
alert("Please try again.");
}
else {
alert("Derp.");
}
}
}
function initChallenge() {
var button = document.getElementById("challengeButton");
button.addEventListener("click", beginAdditionChallenge);
}
window.addEventListener("load", initChallenge);
And here's my attempt to wrap it, which only succeeds in breaking the game, such that the button doesn't even respond:
window.addEventListener("load", function() {
function beginAdditionChallenge() {
var x = Math.ceil(Math.random()*100);
alert(x);
for (var i = 0; i < 3; i++) {
var a = Number(prompt("Provide the first addend.", ""));
var b = Number(prompt("Provide the second addend.", ""));
if (a + b === x) {
alert("Well done!");
break;
}
else if (a + b !== x && i < 2) {
alert("Please try again.");
}
else {
alert("Derp.");
}
}
}
function initChallenge() {
var button = document.getElementById("challengeButton");
button.addEventListener("click", beginAdditionChallenge);
}
window.addEventListener("load", initChallenge);
});
Functional code is available on JSFiddle here.
Note that the onLoad option in JSFiddle does the same as your 2nd snippet. You'll want to choose one of the No wrap options when binding to 'load' yourself.
And, the issue stems from attempting to bind to 'load' within a 'load' handler:
window.addEventListener("load", function() {
// ...
window.addEventListener("load", initChallenge);
});
When the event is already firing and handling the outer binding, it's too late to add more handlers to it. They won't be cycled through and the event shouldn't occur again.
You'll either want to call initChallenge within the outer event binding:
window.addEventListener("load", function() {
// ...
initChallenge();
});
Or, you can use an IIFE with the inner binding:
(function () {
// ...
window.addEventListener("load", initChallenge);
})();

Javascript if clause won't work

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

Categories

Resources