How to use if statements inside a while loop - javascript

I'm very novice at programming and haven't had any luck in finding a tutorial useful for what I want to do.
I am creating a form that will have 2 drop down selections and then one input box which will produce a price depending on the 2 selections.
For the first drop down it will be a type of event. The second will be a selection of adult, child, or student (each selection has its own set ID). Then I want to produce prices dynamically that will appear in a text box based on the user's selections so something sort of like the following (I'm still figuring out JavaScript so bear with me this will be a poor example):
while eventid == 2
{
if registration == adult;
price == 45;
}
Any help would be appreciated.

I agree with the comments that you need to nail down basics - about what you are trying to do and JavaScript itself.
Having said this and based on what you have described, however, I do not think that you need a loop at all. The event type does not sound like a temporal condition for a repeated series of actions until it changes - the classic criteria for a loop.
It sounds like what you need is more like this:
if (eventid == 2) {
if (registration == 'adult') {
price = 45;
} else if (registration == 'child') {
price = 15; // or whatever
}// else if... // more registration conditions
} else if (eventid == 3) { // or whatever
if (registration == 'adult') {
price = 55; // or whatever
} else if (registration == 'child') {
price = 20; // or whatever
}// else if... // more registration conditions
}// else if... // more eventid conditions

I don't think you want a loop, I think the logic that you are looking for is just the if statement, as in "if the registration is an adult, and the event id is 2, then set the price equal to 45" so:
if(eventid == 2){
if(registration == 'adult')
price = 45;
if(registration == 'child')
price = 35;
}
Depending on what you want to do, there could be any number of combinations of logical structures you might employ. A switch statement comes to mind if you have a lot of event ids.

Related

How to keep value from re-calculating when you go back in browser?

I have a multi-page form for making reservations which calculates the number of transportation services required based on a few factors. You first choose a number of passengers ('#input_2_6') and Depending on the type of vehicle you choose is how many vehicles you will need, so when you choose a vehicle the "Quantity" field ("#input_2_20") is updated. The on the next page/step, you have to choose if you want a one-way or round trip, so when you choose round trip, the Quantity field is multiplied by two. Then on the next page/step, you are just shown the summary of your order (confirmation page).
The problem is, with the current code, if you are on the confirmation page and decide to go back to the previous page to change something (perhaps you decided you don't want the round trip and only need one-way), the quantity number keeps the new value and now it is multiplied by 2 again when choosing round trip.
jQuery(document).ready(function ($) {
var totalBook;
$('#input_2_12').change(function () {
switch ($(this).val()) {
case 'Escalade|49':
$('#input_2_20').val(1);
totalBook = Math.ceil($('#input_2_6').val() / 5);
$("#input_2_20").val(totalBook);
break;
case 'Suburban|0':
$('#input_2_20').val(1);
totalBook = Math.ceil($('#input_2_6').val() / 6);
$("#input_2_20").val(totalBook);
break;
case 'Van|14':
$('#input_2_20').val(1);
totalBook = Math.ceil($('#input_2_6').val() / 10);
$("#input_2_20").val(totalBook);
break;
}
});
totalBookNew = $("#input_2_20").val();
$('input:radio[name="input_7"]').change(function () {
$('#input_2_20').val(totalBookNew);
if ($(this).val() == 'Round trip'){
$('#input_2_20').val(totalBookNew);
newTotal = totalBookNew * 2;
$('#input_2_20').val(newTotal);
}
else if ($(this).val() == 'One way'){
$('#input_2_20').val(totalBookNew);
}
});
});
I've tried using the value of 'totalBook' from the first function on the second function but it returns undefined, that's why I created totalBookNew...
I really appreciate any help!
Looks like the main issue is after you do the calculations you set the calculated value into the original input field. Your best bet would be to store the calculations elsewhere in hidden html inputs. So you would have an input called something like:
<input type="hidden" id="input_2_20_calculated" value=0>
Then instead of setting the calculated value back into the input set it in the hidden input instead. Hidden inputs will get passed along with the form, so you would be able to use the calculated values. This is why you get the duplication is because every time the calculation is triggered it's doubling the previous calculated value.
totalBookNew = $("#input_2_20").val();
$('input:radio[name="input_7"]').change(function () {
$('#input_2_20').val(totalBookNew); //This line can be deleted
if ($(this).val() == 'Round trip'){
$('#input_2_20').val(totalBookNew); //You can also delete this line
newTotal = totalBookNew * 2;
$('#input_2_20_calculated').val(newTotal);
}
else if ($(this).val() == 'One way'){
$('#input_2_20_calculated').val(totalBookNew);
}
});
As a cautionary side note you should recalculate on the backend. Don't calculate in the front end and trust those calculations on the back end. It's easy to manipulate the form data on submit and post fake numbers.

If statement in a switch

I am working on a question for a course for learning javascript. I am running into trouble trying to add an if statement inside of a switch. I currently have:
var user = prompt("Are you ready for battle?!").toUpperCase();
switch(user) {
case'YES':
if(YES && NO) {
console.log("Great, let's do it.");
} else {
console.log("Bye");
}
console.log("Great! It will be a long exciting battle.");
break;
case'NO':
console.log("Come back when you are ready.");
break;
case'MAYBE':
console.log("Go away. This is only for the brave");
break;
default:
console.log("You obviously do not belong here. It was a simple yes/no question.")
}
The question is this:
Add some if/else statements to your cases that check to see whether one
condition and another condition are true, as well as whether one condition
or another condition are true. Use && and || at least one time each.
The error I am getting is this: ReferenceError: YES is not defined
What can I put in the if's condition to make this work or how do I define YES?
It would appear that you have two problems working against you here.
First is the issue pointed out in comments that you're treating YES and NO like variables, and they aren't. To avoid robbing you of the opportunity to learn by providing a corrected version of your code, I'll only give relevant examples.
var word = "test";
// If we compare against the string literally, it will have an error
// because it's looking for a variable with that name.
if (word === test) { } // ReferenceError: test is not defined
// we fix this by quoting what we're comparing against
if (word === "test") { } // Code inside the block would be executed :)
// But what about checking the value of "test" by itself?
// A string is "truthy", meaning that it passes the conditional test always.
if ("test") { } // Code would be executed always regardless of the content of var word
// Stringing multiple constants together doesn't make sense
if ("test" && "word") { } // This is equivalent...
if (true && true) { } // ... to this, which doesn't make sense
This brings us to the second problem you're trying to solve. The requirements for your problem specify checking if one condition AND another are true, as well as one condition OR another. The problem is that you only have one conditional to check: the status of the variable user.
It only makes sense to test the condition of something if you don't know what it is. Input received from a user is a perfect example. So I'd recommend that you take more inputs from the user such as name, age, gender, shoe size, or anything else. You can then check conditions as follows:
// You would need to store user input in variables username and age previously...
if (username === "vastlysuperiorman" && age < 13) { console.log("You're awfully young!"); }
// Or to only allow people within an age range...
if (age < 13 || age > 31) { console.log("You must be between 13 and 31 years old to play this game!"); }
Once you have multiple conditions to check, you can check them anywhere--inside a function, inside a case statement, inside another if. It doesn't matter. Just add an if block and test the conditions. :)

If Else Statements in Javascript for LiveCycle

I am creating a form on Adobe LiveCycle that adds the numbers in different fields. I need to have the final field (Eligible Assets) add all the previous fields but exclude the sum of three of them and one in specific but only if it is greater than 60000. I've written the script as follows for the first part (to sum all the fields) this is in a field I've titled TotalAssets:
this.rawValue =Cash.rawValue+SavingsAccount.rawValue+ChildrensSavings.rawValue+CheckingAccount.rawValue+ValueHome1.rawValue+ValueHome2.rawValue+ValueVehicle1.rawValue+ValueVehicle2.rawValue+ValueVehicle3.rawValue+BusinessAccount.rawValue+BusinessAssets.rawValue+StocksBonds.rawValue+Retirement.rawValue+CDs.rawValue+OtherInvestments.rawValue+OtherAssets.rawValue;
This has worked fine, but the Retirement value if it is greater than 60000 should not be added into the calculation. This is what I've written (EligibleAssets):
if (Retirement.rawValue > 60000) {
Retirement.rawValue = 0;
} else {
Retirement.rawValue == Retirement.rawValue ;
}
this.rawValue = TotalAssets.rawValue - (ValueHome1.rawValue+ValueVehicle1.rawValue +Retirement.rawValue);
When I save the form as a PDF the first total of the fields calculates correctly but the second field comes up blank.
If you can spot what I'm missing or doing wrong I would really appreciate any feedback. Thank you!
There are two simple problems that I see here.
First problem is that you are using == when you should be using =.
== - check if the left side is equal to the right side. Example: if(x == 5) {
= - set the left side to the value of the right side. Example: x = 5
In the first example we leave x alone, but in the second example we change x to 5.
So your code should look like:
} else {
Retirement.rawValue = Retirement.rawValue;
}
However, when you think about this, this code doesn't actually do anything. Retirement.rawValue will not change.
This leads us to the second mistake in the code, at least, it looks to me like a mistake.
if(Retirement.rawValue > 60000) {
Retirement.rawValue = 0;
}
This actually changes Retirement.rawValue, which might potentially change what's inside the Retirement field of your form. Worse, its possible that the form would look the same, but act differently when some other field calculates, since you've changed its rawValue. That would be a very tough bug to catch.
The solution is to create a new variable: http://www.w3schools.com/js/js_variables.asp
So now we can create a new variable, set that variable to either the retirement amount or nothing, and then add that variable to the other rawValues at the end:
var retirementOrZero;
if(Retirement.rawValue > 60000) {
retirementOrZero = 0;
} else {
retirementOrZero = Retirement.rawValue;
}
this.rawValue = TotalAssets.rawValue - (ValueHome1.rawValue + ValueVehicle1.rawValue + retirementOrZero);
Now we have a number that we can name anything we want, and we can change it however we want, without affecting any code but our own. So we start by checking if our retirement value is greater than 60000. If it is greater, we set our variable to 0. Otherwise, we set our variable to the retirement value. Then we add that variable we made, to the home and value cost.
As a final question, is it supposed to do
if(Retirement.rawValue > 60000) {
retirementValueOrZero = 0;
}
or is it supposed to do
if(Retirement.rawValue > 60000) {
retirementValueOrZero = 60000;
}
Of course, if you are setting it to 60000 instead of setting it to zero, you probably want to name your variable cappedRetirementValue or something like that -- just make sure you rename it everywhere its used!
Hopefully that helps!
Edit: You said you're only adding retirement value if it is greater than 60k, so what you want is this:
if(RetirementValue.rawValue > 60000) {
retirementValueOrZero = RetirementValue.rawValue;
} else {
retirementValueOrZero = 0;
}

Calculations from checkboxes

This is for an Acrobat order form we use at work to calculate the amount of paper needed to print jobs. There are 4 conditions (saddle stitched books, perfect bound books single and double sided, and not books). All use a different formula to calculate paper quantity. I have all the formulas woking as individual programs but am having trouble getting them all together in the order form. My original thought was to put them all into the output field as a long if else statement. Then it occurred to me that I could run them from the checkbox.
Does either of these methods make more sense?
How do I run them from a checkbox and output the answer to field "PaperQty"?
This is the code for saddle stitched books. I want this to run when SS_CB checkbox is checked and the result to show in "PaperQty" field.
// get field values;
var FieldA = this.getField("Qty2").value;
var FieldB = this.getField("NoUp2").value;
var FieldC = this.getField("PageCount2").value;
event.value = ""; // default result;
// test for non-zero divisor;
if(Number(FieldB) != 0) {
event.value = (FieldC * FieldA / 4) / FieldB; // perform division;
event.value = Math.ceil(event.value); // Round up to next larger intiger;
}

Check multiple textarea fields for value using jquery and then perform a function

Basically what I'm trying to accomplish is I want to check multiple dynamic forms on a page. Then if All textareas are empty OR have the default value, perform a function. Otherwise if any of them are not empty without the default value, cancel the function.
I know how to get the total count of the divs/forms or go through each one, sorta. Just can't put it together. I want it to check them all first before doing anything.
if (jQuery("div[id^='statuscontainer_']:last").length == 0){
}
I don't think this would get quite what I need to do. Or either I not sure how to form it into the function I need.
Thanks
You could take this approach
Give each input a similar class, in my example, inputBox
Create a script to add the total of each inputBox length. If that total == 0, take whatever approach, otherwise continue with the script
$('#show').click(function() {
var total = 0;
$('.inputBox').each(function() {
total += this.value.length;
});
if (total == 0) {
// Do whatever if it's empty
} else {
// Do whatever if its not
}
});
???
Profit
Try it
http://jsfiddle.net/kLnHC/
Edit
Though, in your application, you'd probably want to change the event that triggers it to $('#yourForm').submit(function() { rather than a click function.
use
total += $(this).val();
instead of
total += this.value.length;
will check if there is only a " " and/or a \n in your textarea.

Categories

Resources