Assigning String to Variable with If Else Statements - javascript

sorry this is a super basic question, but I'm not too familiar with google script yet so finding answers to these simple tasks is proving to be difficult. In this code, I'm trying to set a string of numbers to a variable based on another variable. AppNaming is the variable I'm trying to assign the numbers to. AppType is already defined earlier in the code, and depending on the type, I need it to take only part of the variable AppNumber. Depending on the AppType, the AppNumber is separated by commas or slashes, hence the indexOf parts. Are if statements not allowed with var functions? I need the var AppNaming to change based on the AppType in order to name a file later on in the code. Thanks for all the help and sorry again if these questions are annoying; I'm still learning.
function AutoFill(e) {
// variables all defined earlier
//Naming code
var AppNaming = if( AppType == '1' ){
AppNumber.substring( 0, AppNumber.indexOf(","))
}
else if ( AppType == '2'){
AppNumber.substring( 0, AppNumber.indexOf("/"))
}
else ( AppType == '3'){
AppNumber.substring( 0, AppNumber.indexOf(","))
}

You can only assign values to variables. Unfortunately, if statements are not values so you can't say var a = if (...) { } but you can say var a = 3
An if statement controls the flow of the application.
var something = 20;
var a;
if (something > 20) {
a = "this block runs if something is greater than 20";
} else if (something < 20) {
a = "this block runs if something is less than 20";
} else {
a = "this block runs otherwise";
}
// The value of 'a' is 'this block runs otherwise' at this point
So in your example, you can assign App.Number.substring(0, AppNumber.indexOf(",") to a variable because that expression will return a value.
I would recommend you to learn the basics of JavaScript.

Related

javascript if else for beginners

I am very new to Javascript, so I am having a hard time figuring out this easy exercise and what I'm doing this wrong. Any help would be greatly appreciated!
You are given two numeric variables: var n = 25; var result = 0;
Their values may change when you submit.
DO NOT EDIT CODE ABOVE THIS LINE.
=================================
Your Challenge:
Using if and else, make decisions based on the values
of n and result with the following rules:
1. When n is even,
set the value of result to result's current value
plus 10.
2. When n is odd,
set the value of result to result's current value
minus the value of n.
3. Do not declare new variables.
4. Be sure your solution works for all values of n and result.
if (n%2 == 0) {result+10;} else {result-n;}
Your problem isn't if/else, the problem is you never set result to the new value. result+10 just results in the value without storing that value anywhere. (In many programming langauges, that would be a syntax error, but JavaScript allows what it calls ExpressionStatement where any expression can be a statement.)
Either use the compound assignment operators (+= and -=), or write a verbose assignment (result = ...).
Side note: It's easier to debug and edit code when statements are on their own lines, suggest:
if (condition) {
trueStuffHere
} else {
falseStuffHere
}
...or any of the several variations on that theme where trueStuffHere and falseStuffHere are on lines of their own.
You may set the result?
if (n%2 == 0) {
result = result + 10;
} else {
result = result - n;
}
Or if you're a bit better:
if (n % 2 == 0) {
result += 10;
} else {
result -=n;
}

Javascript: action when a string is not found in an array of objects (if statement)

var checkStore=function (book) {
for (var i=0; i<BookStore.length;i++) {
if (book==BookStore[i].title) {
var reply= prompt ('Want to add to your cart?'+ BookStore[i].title);
if (reply==='yes') {
Susan.cart.push(BookStore[i]);
}
}
}
}
How to add to my existing code "if the string is not found, then alert the user 'not found!'". Do I used [else] statement or begin a new one? It's not working correctly when I used else-if statement.
You might want to find the book first, then do your logic:
var checkStore = function(book) {
var found;
for (var i = 0; i < BookStore.length; i++) {
if (book == BookStore[i].title) {
found = BookStore[i];
break;
}
}
if (found) {
var reply = prompt ('Want to add to your cart?' + found.title);
if (reply === 'yes') {
Susan.cart.push(found);
}
} else {
alert('not found!');
}
}
var checkStore=function (book) {
if(BookStore.indexOf(book) < 0){
alert('hello, no book');
} else {
for (var i=0; i<BookStore.length;i++) {
if (book==BookStore[i].title) {
var reply= prompt ('Want to add to your cart?'+ BookStore[i].title);
if (reply==='yes') {
Susan.cart.push(BookStore[i]);
}
}
}
}
}
}
The other answers are totally valid. You can also just make return points which stop the execution of the function at logical endpoints.
var checkStore=function (book) {
for (var i=0; i<BookStore.length;i++) {
if (book==BookStore[i].title) {
var reply= prompt ('Want to add to your cart?'+ BookStore[i].title);
if (reply==='yes') {
Susan.cart.push(BookStore[i]);
return "book added to cart."
}else{
return "book found, but not added to cart."
}
}
}
return "bummer, book not found.";
}
alert(checkStore("book title"));
Fastest solution
This is the shortest way to take your exact existing code and add a few lines and solve this problem: How to add to my existing code "if the string is not found, then alert the user 'not found!'".
var checkStore=function (book) {
var bookWasFound=false; //Line added here
for (var i=0; i<BookStore.length;i++) {
if (book==BookStore[i].title) {
bookWasFound=true; //Line added here
var reply= prompt ('Want to add to your cart?'+ BookStore[i].title);
if (reply==='yes') {
Susan.cart.push(BookStore[i]);
}
}
}
if (!bookWasFound) { //Line added here
alert('Not found!'); //Line added here
} //Line added here
}
Explanation and alternatives
Why don't we use an else statement?
You ask, "Do I used [else] statement[...]?"
You do not. You can not! The reason is because the else part of an if-else statement is executed when the if part is not executed. So if we put that in our loop, every time we compare a book title to the string we're looking for, our else would be executed if the book title didn't match. We only want that to happen once.
It is somewhat difficult to think about this scenario without a concrete example, so I will show what happens if we use an if-else statement.
The code would look like this:
if (book==BookStore[i].title) {
...
} else {
alert('Not found!');
}
Imagine that our BookStore is populated with 3 books: "The C Programming language", "JavaScript: Pocket Reference", and "Everybody Poops".
If the checkStore function is passed in "JavaScript: Pocket Reference". Our loop will go like this:
As soon as we enter the loop, book would be equal to "JavaScript: Pocket Reference", and i = 0 so BookStore[i].title is the same as BookStore[0].title, and the 0th book's title is "The C Programming language".
So the line if(book==BookStore[i].title) { would compare "JavaScript: Poc..." to "The C Prog..." and evaluate to false.
Since the if evaulated to false, the else part gets executed. The else part is alert('Not found!').
Now, we have finished one iteration of our loop, and we compared the string passed in to the first book's title which didn't match, so we gave the alert. But we shouldn't have! If we just kept going, we would see that the second book's title matched, so we shouldn't have told the user that the book wasn't found. It is correct that the book wasn't found, yet, but we should have waited before we announced this to the user.
I may have went into great detail to explain my point, but I believe it is very important. This is one example of when it takes thinking like a programmer or thinking algorithmically to solve the problem.
You have to think about the problem and ask yourself, "How do we know if a book is in the list?". Well, a book is in the list if its title is the same as the title of any book in the list. Because we have to use the word any when we say "...any book in the list", we know that our algorithm must test every book in the list.
We can't tell the user that a book was found, or not found, until we have tested every book in the list, or in our BookStore. We can't tell the user that a book was found, or not found, until our loop has finished.
So what do we do?
You will see this situation over and over again during your programming experience. You need to iterate over a list, and determine if something is in the list.
You can't ever know until you've iterated over every single object in the list, but once you have, how do you know the answer?
The solution is to use what is commonly referred to in programming, a flag. A flag is a variable that has two possible states: true, or false, on or off, yes or no, 1 or 0. It doesn't matter what you call the states. At any time, the flag can only be in one of the two possible states.
We can use a flag by setting it to one state, usually false or 0, then looping through some list and if (...) we set it to true. Each iteration of the loop, if some condition is met, we set our flag to true, and at the end of the loop, we know that the condition was met at some point in the loop, if the flag is true.
The most common way to implement a flag, is to use a boolean variable. That is, a variable which can only be set to true or false. In Javascript, there isn't a boolean variable since any variable can be set to any value. So we just use a regular variable, but still only set it to true or false.
We do that like this:
var myFlag = false;
// OR
var myFlag = true;
So a simple usage of a flag could be to determine if there exists an even number in a given array.
Just like this:
var myArray = [1, 3, 5, 123, 125, 4, 89, 8, 10];
var hasEven = false;
for(var i = 0; i < myArray.length; i++) {
if( myArray[i] % 2 == 0 ) {
hasEven = true;
}
}
if(hasEven) {
alert('Found an even number!');
} else {
alert('Did not find an even number!');
}
Note that you can test the value of a boolean (true or false) variable with if(variableName), you don't have to include the == true like if(variableName == true).
Final implementation
Now we can use our flag to solve our original problem
var checkStore = function(book) {
var bookWasFound = false;
for (var i = 0; i < BookStore.length; i++) {
if (book == BookStore[i].title) {
// If we get in this loop, we must have found a match,
// so we should set our flag to true now
bookWasFound = true
var reply = prompt ('Want to add to your cart? ' + BookStore[i].title);
if (reply === 'yes') {
Susan.cart.push( BookStore[i] );
}
} // End of if statement for prompt
} // End of loop looking for book
if( !bookWasFound ) { // Same as if( bookWasFound == false )
alert('Not found!');
}
} // End of function
Using this flag allows us to keep the inside of the for loop very clean and organized, and handle the results outside of it.

keep add the value without overwrite the function

function checkData() {
var temp = 0;
var totalMarks = countMark(temp);
if (totalMarks != 100)
window.alert("Marks must total 100");
}
function countMark(mark) {
var totalMark = 0;
totalMark += parseInt(mark)
return totalMark;
}
function doAdd() {
var taskid = document.getElementById("taskid").value;
var taskname = document.getElementById("taskname").value;
var taskmark = document.getElementById("taskmark").value;
if (taskid.length === 0)
window.alert("Task Id cannot be empty!");
if (taskname.length === 0)
window.alert("Task name cannot be empty!");
if (taskmark.length === 0)
window.alert("Task Mark cannot be empty!");
else if (!markpattern.test(taskmark))
window.alert("Invalid data in mark field");
var marks = parseInt(document.getElementById("taskmark"));
if (marks < 0 || marks > 100)
window.alert("Marks out of range. Please re-enter");
countMark(marks);
}
My question is when i keep call the doAdd() function. my marks will keep adding . want to do like passing reference like in C++ . my function countMark(...) will keep adding .
after that, when my form submitted, my form will call the function checkData()
If my totalmark is not 100 . will prompt out the alert and error.
but my code is not working . I guess that my countMark function wrong somewhere
If I understand you correctly, you're looking for the equivalent of a static variable - something that gets initialized the first time the function is called, and keeps it's value for subsequent calls.
Take a look at this related question: https://stackoverflow.com/a/1535650/2444111
The top answer (by CMS) is talking about class-based static variables, which are not quite the same thing.
The second answer (by Pascal MARTIN) is what you're looking for. It takes advantage of the fact that JS functions are also objects, and stores the variable as a property of the function object. This is a better solution than using a global variable (or a property of window, which is what a global actually is)
There are several issues in your code and it's really hard to say what your intention was. But I will address what I found.
In the following piece of code you are requesting a DOM Element and try to parse it as an Integer. The result of that type convertion is always NaN. Maybe wanted to get the value attribute of your element, like you did before. (Also, don't request the same element multiple times. Request it once, save the result in a variable and use that variable from that on).
var marks = parseInt(document.getElementById("taskmark"));
if (marks < 0 || marks > 100)
window.alert("Marks out of range. Please re-enter");
countMark(marks);
Your function countMark is pretty useless, because it will always return whatever Number you pass to it (see comments in your code).
function countMark(mark) {
var totalMark = 0; //create a new variable with value 0
totalMark += parseInt(mark) //add "mark" to that variable
return totalMark; //return that variable => 0 + mark = mark (and if mark = NaN => 0 + mark = NaN)
}
Maybe you wanted to make totalMark a global variable, than you would need to define it outside of your function:
var totalMark = 0;
function countMark(mark) {
totalMark += parseInt(mark);
return totalMark;
}
Last but not least, lets analyse your function checkData:
function checkData() {
var temp = 0; //create a local variable with value 0
var totalMarks = countMark(temp); //pass 0 to countMark => return 0 => totalMarks = 0
if (totalMarks != 100) //always true since totalMarks is always 0
window.alert("Marks must total 100"); //will always alert
}

Why does this JQuery only work if I console.log a bad variable? [duplicate]

This question already has answers here:
Why does this append only work if I console log a bad variable
(2 answers)
Closed 9 years ago.
I am relatively new with jquery, and am trying to change an up and down arrow on a js accordion on each click, unfortunately, I have run into an error where it only works if I console.log a bad variable. Does anyone have any guidance as to what I might be doing wrong when I onclick="embiggen(1)" for example if its accordion id one?
There are some other issues surrounding the html, but specifically why is this only working if I console.log;?
function arrowup(id){
$('#downarrow'+id).remove();
$('#dropdown'+id).append('</a>');
$('#dropdown'+id).append('<i id="uparrow'+ id +'" class="icon-1 icon-chevron-up">');
}
function arrowdown(id){
$('#uparrow'+id).remove();
$('#dropdown'+id).append('</a>');
$('#dropdown'+id).append('<i id="downarrow'+ id +'" class="icon-1 icon-chevron-down">');
}
//Switches the arrows
function embiggen(id){
var up = $('#uparrow'+id).length;
if (up == 1){
arrowdown(id);
console.log(i see you);
}
var down = $('#downarrow'+id).length;
if (down == 1){
arrowup(id);
}
}
The bad console.log() makes it "work" because the error breaks the script execution before entering the second if statement.
Fixing the real issue
down == 1 is always true. You should use an else statement:
if ($('#uparrow'+id).length){
arrowdown(id);
} else if ($('#downarrow'+id).length){
arrowup(id);
}
Understanding it
down == 1 is always true independently of up == 1. Here's your logic explained in pseudo-code in both scenarios:
var up = 1, down = 0;
if (up) { down = 1; up = 0; } //enters this block, down now is 1
if (down) { down = 0; up = 1; } //enters this block as down == 1
var up = 0, down = 1;
if (up) { down = 1; up = 0; } //doesn't enter this block
if (down) { down = 0; up = 1; } //enters this block as down == 1
You just have put an else in there so the execution flow does not enter the second if statement in case the first one succeeds.
if (up) {}
else if (down) {}
Truthy/Falsy values
To explain why I'm using .length isolated inside the conditional statement: in JavaScript, the number 0 is a falsy value and 1 is truthy, hence these can be used directly inside the if statement and it will be interpreted based on the internal ToBoolean algorithm logic. Obviously you can == 1 if you feel like, that's more clear though slightly redundant.
A possibly simpler way around
Going a little off-topic, but your goal can most likely be achieved in an easier way. I may be oversimplifying your logic, but depending on your intents you may just toggle between those two classes:
function embiggen(id) {
$('#arrow'+id).toggleClass('icon-chevron-up icon-chevron-down');
}
Then, you'd no longer have to create a new #downarrow/#uparrow element each time the function is called. If said arrow has JS behavior attached, you can check which logic to execute through an if statement using hasClass().
It works because when an error occurs, JavaScript skips the rest of your function body.
The problem in your case is that the function arrowdown() creates #downarrow+id, making the next condition truthy and calling the function arrowup().
You either need an alternative branch, using Fabricio's answer, or return immediately after making changes to the DOM that would otherwise change the state:
function embiggen(id) {
if ($('#uparrow'+id).length) {
return arrowdown(id);
}
if ($('#downarrow'+id).length) {
return arrowup(id);
}
// ehm, something else happened?
}

getting values and assigning them to a hidden field

I have the following function that is suppose to take a value from a field in a form and assign it to a hidden field when its called. for some reason its not working and I cant give you more details on why its not working simply because javascript doesnt really tell you much about whats wrong.
function clickChange(stype){
if(stype == '1'){
var fValue = document.getElementById('checkB1').value;
if(fCatValue == 0){
fCatValue = fValue;
}else{
fCatValue = 0;
}
document.getElementById('cat_1').value = fCatValue;
}elseif(stype == '2'){
var sValue = document.getElementById('checkB2').value;
if(sCatValue == 0){
sCatValue = sValue;
}else{
sCatValue = 0;
}
document.getElementById('cat_2').value = sCatValue;
}
}
You need to convert the values to integer, or treat them as a string:
either:
var fValue = parseInt(document.getElementById('checkB1').value)
if(fCatValue == 0){....
or
var fValue = document.getElementById('checkB1').value;
if(fCatValue =='0'){...
Because of the placement of your declaration of the variable sCatValue it looks like sCatValue goes out of scope (or doesn't get declared at all).It would probably be easier on you if you declare all of your function scoped variables at the beginning of your function and cut down on the number of nested if statements.
I'd also recommend you use self explanatory variable names to cut down on confusing yourself. Also I'd recommend walking through your code with the use of a javascript debugger like firebug or ie 9's built in one. (surprising I know). And using jshint to help out with the common rules.
I found some other bugs and cleaned things up a bit and this is what I got
function clickChange(stype) {
//declared at the start so no scope undefined issues
var sValue = document.getElementById('checkB2').value;
var fValue = document.getElementById('checkB1').value;
//changed the comparision op from == to ===
//in javascript '===' throws false if the types compared are not the
//same otherwise it attemps to preform implicit casting for you
if (stype === '1') {
//parsing to insure that the types are matching
//the 10 is a radix param. It insures your number is formatted as a decimal
if (parseInt(fCatValue,10)=== 0) {
fCatValue = fValue;
} else {
fCatValue = 0;
}
document.getElementById('cat_1').value = fCatValue;
} else if (stype === '2') {
if (parseInt(sCatValue,10)=== 0) {
sCatValue = sValue;
} else {
sCatValue = 0;
}
document.getElementById('cat_2').value = sCatValue;
}
}

Categories

Resources