JavaScript "if" statement wont run - javascript

(Using Javascript)
If I enter text in the textbox or not, the alert will not come up.
I know this is a simple fix but I can not figure it out!
(This is for learning purposes.)
Workout Log Test
<script type="text/javascript">
function myResults() {
myExercise();
myWeight();
mySets();
myReps();
myFunction();
}
function myExercise() {
var txtExercise = document.getElementById("txtExercise");
var txtOutput = document.getElementById("txtOutput1");
var name = txtExercise.value;
txtOutput1.value = "You destroyed, " + name + "!"
if (txtExercise.length === 0) {
alert ('Do you even lift?');
return;

First off, you're checking the "length" property of the element rather than the value of the input.
Second of all, you're checking against an integer value. If you were to simply read the value of the element, you're going to get text.
I'm guessing, what you want is something like:
var exercise = parseInt(txtExercise.value, 10);
if(exercise === 0) {
alert('Do you even lift?');
return;
}
But that's assuming txtExercise is an input element. Without seeing your markup, it's hard to be sure that any given answer will work.

Here you go, all fixed. You need an event handler, and this is a better if/else use case.
http://codepen.io/davidwickman/pen/vOKjqV
// Check the .value.length instead of just the .length
if (txtExercise.value.length === 0) {
alert('Bro, do you even lift?');
} else {
txtOutput1.value = "You destroyed, " + name + "!";
}

Assuming you have closed the function and if statement properly, you are missing a semi colon just before the if statement.
txtOutput1.value = "You destroyed, " + name + "!"; <---- here

Related

Javascript - Waiting for user input (callbacks)

I've been looking at other questions trying to get my head around callbacks but I just can't make sense of it enough to use in my context. I'm writing a text based game which uses purely text input. When needed, I want the game to ask a question with a varying amount of answers and then wait until a valid response is given. Below is an example that doesn't work but explains what I'm trying to do. Can anyone provide me with any guidance? Thanks.
//main code
pEQUIP = ["foo", "foo", "foo"];
exItem = "ball";
function prompt(numPrompts, callback) {
//waits until user types a number <= numPrompts and presses enter, then returns the valid result entered
}
$('#gametext').append("<p>" + "What slot would you like to use to hold this item?" + "</p>");
//where a function would be stopping the code until a valid answer is given
if (prompt == "1") {
pEQUIP[0] = exItem;
} else if (prompt == "2") {
pEQUIP[1] = exItem;
} else if (prompt == "3") {
pEQUIP[2] = exItem;
}
//Just a quick n dirty way of testing it worked below:
$('#gametext').append("<p>" + pEQUIP[0] + pEQUIP[1] + pEQUIP[2] + "</p>");
//parses user info unsure if this could be used or would have to be copied
$(document).ready(function() {
$(document).keypress(function(key) {
if (key.which === 13 && $('#userinput').is(':focus')) {
var value = $('#userinput').val().toLowerCase();
$('#userinput').val("");
//playerInput(value); Is usually here, would lead to
//a switch which parses commands typed by the user.
//Unsure if it can be used for this problem as pausing
//the code I think would stop the switch?
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="gametext"></div>
<input id="userinput">
</body>
It appears as though you're thinking of functions incorrectly.
Functions are:
A series of steps that may return data when they're invoked. You
invoke a function by passing arguments to the function name, even if
the arguments are nothing () - a.e. alert(string) or myFunction()
Not comparable to anything but themselves. In your code you have prompt == "1" this isn't going to work. prompt is a function name and it isn't invoked so you are literally comparing the function itself to the string "1".
Able to return data when invoked. That data can be compared.
Note: Also, very importantly, prompt is the name of a default function(like alert or console) and you shouldn't overwrite it. It isn't considered a reserved keyword by the language but altering it will cause havok if any other library you're using, or any other programmer doesn't know it's been overwritten, and tries to invoke it.
prompt("this is a normal prompt");
Furthermore you have the document setup to check the value of the text box itself on keypress. You should probably change this to an event listener on the text box, but there isn't any reason to continuously loop a function beyond this while waiting for the box to match some predefined input.
The Flow is this:
type in the box
hit enter
check value
if value is 1 or 2 or 3 or any other acceptable answer do something
If that's all you need currently then you do not need to work so hard for the functionality when a single event listener could do the trick:
$("#input_box").on("keypress", function(e) {
if(e.keyCode === 13) {
let value = $("#input_box").val();
if(value === "1" || value === "2" || value === "3") {
//do whatever
}
}
});
$("#input_box").on("keypress", function(e) {
if(e.keyCode === 13) {
let value = $("#input_box").val();
if(value === "1" || value === "2" || value === "3") {
console.log("accepted");
}
$("#input_box").val("");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input_box">

JavaScript not recognizing variable

I'm new to Javascript and struggling to figure out why this piece of code isn't working for me.
Essentially I'm defining a variable, yet when I go to use that variable in an IF or Switch statement, it doesn't seem to be able to match the contents of the variable. No errors, the IF statement just doesn't get satisfied. While with the Switch, it always falls through to the default setting, as it can't match the contents.
I have a Print statement in place after the variable is defined, and it does display the contents of the variable correctly.
I'm really at a loss as to why the print can return the value of the variable, yet the IF and Switch can't find it.
Below is the snippet I'm working from. The variable is "strWilma", which doesn't get reflected properly in the Print second value statement, but not in the IF.
for (var i=0; i < Flinstones.length; i++)
{
if (Flinstones[i].startsWith("?"))
{
// Convert the Secondary field map to a Properties item, for easier navigation
var objSecondaryFieldMap = PropertiesFromString(strSecondaryFieldMap);
// Map all of the Secondary values
var arraySecondaryFields = objSecondaryFieldMap.keys();
while (arraySecondaryFields.hasMoreElements())
{
strFred = arraySecondaryFields.nextElement();
strWilma = objSecondaryFieldMap.get(strFred);
print("TargetType:" + Object.prototype.toString.call(strFred));
print("SourceType:" + Object.prototype.toString.call(strWilma));
print("Text Type:" + Object.prototype.toString.call("hardcoded value"));
print("First Value:" + objItem.getNewFieldValue(Flinstones[i].substring(1)) );
print("Second Value:" + strWilma );
if (objItem.getNewFieldValue(Flinstones[i].substring(1)) == strWilma)
//if (objItem.getNewFieldValue(Flinstones[i].substring(1)) == "hardcoded value") // WORKS
{
print("It Worked!!!");
}
}
}
}
}
Thanks

Nested If-else statements being skipped

What I'm building is a game where the computer generates a random number (1-100) and the user must guess the correct number. The goal is for the computer to compare the current guess to the previous guess and spit out a statement: "hot", "cold", "hotter", "colder", etc.
My Code (focus on the JS): CodePen fiddle
//global variables--computer generated guess, and guess log
var answer = Math.floor((Math.random() * 100)+1);
var guessArray = [];
var index = 0;
//user clicks submit button and guess is registered by computer
$("#submit").click( function(){
var guess = $("#guess").val();
guessArray.push(guess);
//prints out the answer and user guesses
$("#answer").text("Answer:" + " "+ answer);
$("#guessArrayPrint").text("You guessed: " + " " + guessArray + " ");
if (answer === guess) {
$("#statement").text("woo hoo right answer");
} else {
var currentDifference = Math.abs(answer-guess);
var currentDiffArray = [];
currentDiffArray.push(currentDifference);
if (index = 0) {
//if-else statement comparing current guess range to answer
if ( currentDifference >=1 && currentDifference <= 10){
$("#statement").text("Ouch! You're hot!");
} else {
$("#statement").text("Brr! You're cold!");
}
} else {
//if-else statement comparing current guess to previous guess
var previousDiff = answer- prevguess;
var prevguess = guessArray [i-1];
if( previousDiff < currentDifference){
$("#statement").text("Ahh! Getting Warmer!");
} else {
$("#statement").text("Brrr...getting colder");
}
}
index++
}
});
My nested if-else statements are not working. When a user inputs a guess, no matter how close to the answer, it always returns the statement "brr.. getting colder", which is in the "else" section.
Ideally when the user inputs their first guess if (index = 0) should run then when the second guess is input, it should move to the "else" statement with the previous guess variables. I tried moving around the variables, changed orders of if/else, and thought maybe it's the placement of index++. Nothing is working. Not sure if something is wrong with my variables , arrays, or the syntax of my if/else statements.
tl;dr: when the program is run only the "else" portion of the nested if-else statement is run. Not sure how to fix… I've gone through my code a number of times. The syntax, the arrays, and variables. Uncertain what's wrong.
You JS has if (index = 0). This should be if (index === 0).
Additionally, you need to cast the value of your input field to a number. You can do this using:
var guess = +$("#guess").val(); // + cast as a number
More syntax errors:
prevguess = guessArray[i - 1] --> prevguess = guessArray[index - 1];
Here is a partial working Fiddle. I ran through some scenarios, and the fiddle really only works if you give the application the right answer. The code has many syntax errors, bad refs and calculations. I would suggest opening the console or a debugger, identifying those issue, and fixing them.
Here is a Fully Functional Demo.

Onclick function for all members of a class

I'm making a two-column math page, with theorems and definitions on the left side, and additional explanations on the right side.
The way that the user accesses the explanations is by clicking on text of the class "explainable".
After the page loads, I run a script to give each "explainable" element its own onclick function, which hides the text on the right panel (if any) and refills it with the clicked's elements explanation.
But when I try and run it, it tells me that the explainable element is undefined.
Here is the relevant function and an example of the text with the class:
function
<script type="text/javascript">
window.setTimeout(makeExplanations, 3000);
function makeExplanations(){
var explainables = document.getElementsByClassName("explainable");
var currentlyShowing = "";
for(var i = 0; i < explainables.length; i++){
console.log("id: " + explainables[i].id);
var element = explainables[i];
explainables[i].onclick = function(){
if(currentlyShowing != ""){
document.getElementById(currentlyShowing + 'e').style.display = "none";
}
var explanationDiv = document.getElementById(explainables[i].id + 'e')
explanationDiv.style.display = "inline";
explanationDiv.focus();
currentlyShowing = explainables[i].id;
};
}
}
</script>
I have it waiting 3 seconds to execute because doing body onload=makeExplainables() wasn't sufficient. (Might have something to do with the way that the MathJax loads - I'm not sure.)
example of explainable class
<span class="explainable" id="595858535">so either statement is vacuously true</span>. Thus, $X = Y$ holds,
and hence we declare that there exists only one set with no elements.</p>
and the explanation it reveals
<div id="595858535e" style="display: none;">
<p>An if-then statement (a conditional) is vacuously true when the if portion is false in all cases.
For example, the statement "If 2 + 2 = 5, then pigs fly" is vacuously true, since its
antecedent (if 2 + 2 = 5) is always false.</p>
<p>In this case, the conditional in question is "there exists some $x \in X$ such that $x \notin Y$".
But since $X$ is an empty set, there does not exist any $x \in X$ such that anything. Hence, the
statement is vacuously true in all cases.</p>
<p>Another way to think about it is this: a conditional is only falsified if its antecedent ("if ...") is true
and its consequent ("then ... ") is false. If the antecedent is always false, then this can never happen.
Thus the statement as a whole is always true.</p>
</div>
Error in Firebug when I try to click on the explainable text:
16:23:44.704 "id: 595858535" zfc:89
16:23:44.704 "id: 595858536" zfc:89
16:23:53.045 TypeError: explainables[i] is undefined zfc:95
The real reason for that error is that "i" has already reached a value equal to the array's length, when the click handler is called. Hence explainables[i], i.e. explainables[explainables.length] is undefinded.
JS fiddle with console logs to explain you better: http://jsfiddle.net/wV4Lh/6/
element.onclick = function(){
// length of array is 2 for this example
console.log("explainables length: " + explainables.length);
// value of i is 2 in the click handler
console.log("i: " + i);
// explainables[i] = explainables[2] is undefined
console.log("explainables[i] - ith: " + explainables[i]);
// explainables[0] is valid
console.log("explainables[0] - 0th: " + explainables[0]);
// explainables[1] is valid
console.log("explainables[1] - 1st: " + explainables[1]);
};
This clearly shows that explainables is well in scope of the click handler, but value of i = length of the array as the 'for' loop has already completed it's full execution way before the click event is triggered.
P.S: The difficulty in initially understanding this behavior of a handler is due the counter-intuitive way a handler works, i.e. it is not executed in sequence with other code surrounding it. A handler only get's executed when corresponding event is triggered and not in sequence with in the for loop, in this case.
So, I finally got it work by changing the explanation[i] in the onclick function to this.
I thought that I was making a closure wherein the explanation[i] variable would be accessible from within the onclick function even after makeExplanations() ended, but I guess that is incorrect.
The corrected onclick function looks like this:
explainables[i].onclick = function(){
if(currentlyShowing != ""){
document.getElementById(currentlyShowing + 'e').style.display = "none";
}
var explanationDiv = document.getElementById(this.id + 'e')
explanationDiv.style.display = "inline";
explanationDiv.focus();
currentlyShowing = this.id;
};

Seeing if input matches array if not alert

var tagAllowed = true;
var allowedTags =["Person","People","Dance","Word"];
if(tagAllowed === true) {
for(var i=0;i<allowedTags.length;i++){
var aTags = allowedTags[i];
if(input.val().toLowerCase() === aTags.toLowerCase()) {
tagged.append('<span unselectable="on" class="tagged '+colorize+'" title="Click To Delete">'+inputVal.trim()+'</span>');
tagSize = $('.tagged').length;
var ele = $('.tagged').last(),
subtract = parseInt(ele.outerWidth(true),10);
input.width(input.width() - subtract);
tagged.width(tagged.width() + subtract);
input.css('marginLeft','5px');
input.val("");
input.css('color','#000');
} else {
errorMess.children('span').remove();
errorMess.prepend('<span>'+errorProcess+'<span>');
errorMess.slideDown();
}
}
The following code works in a way, if the input.val() does not match it will show the custom alert errorMess and well even if the word matches it still shows the custom alert. I am wondering if maybe I am doing something wrong in my conditional. As I don't need the custom alert to appear if the words match.
If any suggestions please post. I know this isn't the best example with just a code, but I hope all of you get what I am trying to say. I just don't want the custom alert to appear if the two words match together.
You have the if-statement inside the for-loop. The input value will never equal more than one of the tags in the array. You could use a for-loop to set a boolean. Then the if-statement could follow the for-loop.
boolean isAllowedTag = false;
for(var i=0;i<allowedTags.length;i++){
var aTags = allowedTags[i];
if(input.val().toLowerCase() === aTags.toLowerCase()) {
isAllowedTag = true;
break;
}
}
if (isAllowedTag) {
// ...
} else {
errorMess.children('span').remove();
errorMess.prepend('<span>'+errorProcess+'<span>');
errorMess.slideDown();
}
}
add a break; after your input.css('color, '#000'); line. also, you should really change those last 3 lines to: input.val("").css({marginLeft:'5px', color:'#000'});. Making calls to .css() is slow, so it's better to do as much as you can in one call.

Categories

Resources