If Else Statements in Javascript for LiveCycle - javascript

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;
}

Related

double conditions in if statement

as I'm not that good in coding i have a small issue in my code that i need to find a solution for it. my code bellow that i made is to transfer data from one sheet to another one based on value on a specific cell, that it's working perfectly, but for another case that i have i need to make double conditions for my if statement that they need to be both of them true so it can work, first condition it's the one that i already made, and the second one is i want to check if the cell number 12 is not empty.
for (i = 1; i < dataValues.length; i++) {
if (dataValues[i][11] === 'COMMANDE CONFIRMER' && ) {
pasteSheet.appendRow([dataValues[i][0],
dataValues[i][1],
dataValues[i][2],
dataValues[i][3],
dataValues[i][4],
dataValues[i][5],
dataValues[i][6],
dataValues[i][7],
dataValues[i][8],
dataValues[i][9],
dataValues[i][10],
dataValues[i][11]]);
var clearRow = i + 2;
copySheet.getRange('A' + clearRow + ':L' + clearRow).clearContent();
}
}
Column L is probably [i][11]
Based up what you added in the comment below I'd say that this is probably what you are after.
if (dataValues[i][11] === 'COMMANDE CONFIRMER' && dataValues[i][12]) { so then all you need is to make sure it's not empty. Or it's also possible that you not really sure what you want so let us know.

How to swap two numbers using javascript function with one parameter

My Requirement is
I want to display this output when I gave a(0) the output should come 5 and when I gave a(5) the output should come 0.
a(0) = 5
a(5) = 0
like this
Hint:
Using this function
function A(num){}
like this
Please Help me how to do this I'm new in JS
Please give me different kind of solutions its more useful to my career.
function swap (input) {
if( input == 0)
return 5;
return 0;
}
i think there is no description needed
I think I see what you are getting at.
You want to input one variable into a function, and return another variable that is not defined yet. Then you want to define that variable by inputting it into the same function, and get the first input as the output. And so you should end up with 2 outputs.
Now this is technically impossible, because there are undefined variables at play. However, programming is about imagination and I think I have a solution (it's technically a hack but it will work):
var i = 1;
var output1;
var output2;
function swap(input) {
function func1(input) {
output2 = input;
i++;
}
function func2(input) {
output1 = input;
i = 1;
alert(String(output1) + "\n" + String(output2));
}
if (i === 1) {
func1(input);
}
else if (i === 2) {
func2(input);
}
}
while(true) {
swap(prompt("Enter your first input (this will be your second output):"));
swap(prompt("Enter your second input (this will be your first output):"));
}
The swap function goes back and forth between the values 1 and 2 in the variable i. That is how it keeps track of first or second inputs and their exact opposite outputs. The input, or parameter of the swap function is whatever the user types into the prompt boxes. Feel free to make it user-friendly, this is just the dirty code behind it. The reason they are outputted together is because the second input is undefined, and so the machine cannot guess what you were going to input. So first my little program collects all the data and just reverses the order when it is time to output. But to the user who knows nothing about JavaScript and what is going on underneath the hood, this would work perfectly in my opinion.
This should work for any data types inputted, I tested it myself with objects, strings, numbers, and arrays. Hope this helps!!
Shorter alternative to #mtizziani's answer:
let swap = x => !x * 5 // yes this is all
console.log(swap(0));
console.log(swap(5));
We toggle the input, so x is now 1 or 0
We multiple by 5.
Job done.

attribute maxlength of input field is changing, but input doesn't care

I have a function to limit the number of characters that a user can type into an input field for my game. It works, except that if it goes down by 1 or more in length, the user can still enter 1 or more characters than they should be able to.
I check the inspector, and it even shows maxlength changing correctly. However, for whatever reason, it still lets the user enter in a length equal to the max number of characters that the variable was equal to during the same session. Is it a bug? Any way to get it working correctly?
my_var = 150000; //this var changes often, can go down to 0 or up to 1000000000
function limitNumberOfCharacters() {
x = my_var.toString().length;
$('.my_input_class').attr('maxlength', x);
}
limitNumberOfCharacters(); //this gets called often
EDIT: http://jsfiddle.net/mDw6f/
EDITTTT:
You are using x as a global variable and is probably getting changed from something else in your code. Use var x = my_var.toString().length; (emphasis on var)
Honestly after seeing this code I was afraid there would be many more underlying problems but all I did was add var before the xyz and it works just as you want it to.
Also fixed the issue of the previous bet amount returning to the input field. It now results to a blank field.
Cheers
Real Fiddle Example
Try using this fiddle:
Working Demo
Use the html input like I did in the code, no need to specify the maxlength attribute to it.
<input type="text" class="my_input_class"/>
and the script
my_var = 25; //this var changes often, can go down to 0 or up to 1000000000
function limitNumberOfCharacters() {
x = my_var.toString().length;
$('.my_input_class').attr('maxlength', x);
}
limitNumberOfCharacters();

Javascript if statement not working as intended

If you look here and try to click on the voting arrows, you'll see my problem. Now compare that to the homepage (click logo). Try voting there. The arrows change image based on vote. I also use a in_array() function to determine what the user has voted on and it produces the correct voting icon. This all works fine on the submission page I linked to. However, again, if you try clicking on the links, it always defaults to the else statement in this Javascript function:
I'll only show the function for liking, as I'm having the identical problem for the dislike.
function getVote(filename, num, idnum, user)
{
var like = document.getElementById('like_arrow' + num);
var dislike = document.getElementById('dislike_arrow' + num);
if (like.src.indexOf('../vote_triangle.png')!=-1 && dislike.src.indexOf('../vote_triangle_flip.png')!=-1) {
like.src = '../vote_triangle_like.png';
(AJAX to alter rating here)
} else if (like.src.indexOf('../vote_triangle.png') != -1) {
like.src = '../vote_triangle_like.png';
dislike.src = '../vote_triangle_flip.png';
(AJAX to alter rating here)
} else {
like.src = '../vote_triangle.png'; // Always defaults to this
(AJAX to alter rating here)
}
}
In case you're wondering, the num variable is what I use on the front page to differentiate between the submissions, they increment by one for each one. In this though, I just made that value blank in the function so it shouldn't affect anything. Might be my problem though, but I can't see how.
Thanks!
like.src isn't going to contain ..\. It may be as simple as removing that part.

How to loop through elements and call onblur handler for certain elements

I have a case where I have a bunch of text boxes and radio buttons on a screen all built dynamically with various DIVs. There are onblur routines for all of the text boxes to validate entry, but depending on the radio button selection, the text box entry could be invalid when it was valid originally. I can't use onblur with the radio buttons because they could go from the radio button into one of the text boxes that was made invalid and create an infinite loop since I'm putting focus into the invalid element. Since each text box has its own special parameters for the onblur calls, I figure the best way to do this is to call the onblur event for the textboxes when the form gets submitted to make sure all entry is still valid with the radio button configuration they have selected. I also need it to stop submitting if one of the onblur events returns false so they can correct the textbox that is wrong. This is what I've written:
for (var intElement = 0; intElement < document.forms[0].elements.length; intElement = intElement + 1)
{
if (document.forms[0].elements[intElement].name.substr(3) == "FactorAmount") // The first 3 characters of the name are a unique identifier for each field
{
if (document.forms[0].elements[intElement].onblur())
{
return false;
break;
}
}
}
return true;
I originally had (!document.forms[0].elements[intElement].onblur()) but the alert messages from the onblur events weren't popping up when I had that. Now the alert messages are popping up, but it's still continuing to loop through elements if it hits an error. I've stepped through this with a debugger both ways, and it appears to be looping just fine, but it's either 1) not stopping and returning false when I need it to or 2) not executing my alert messages to tell the user what the error was. Can someone possibly help? It's probably something stupid I'm doing.
The onblur method that is getting called looks like this:
function f_VerifyRange(tagFactor, reaMin, reaMax, intPrecision, sLOB, sIL, sFactorCode)
{
var tagCreditOrDebit;
var tagIsTotal;
var tagPercentageOrDecimal;
eval("tagCreditOrDebit = document.forms[0]." + tagFactor.name.substr(0,3) + "CreditOrDebitC");
eval("tagIsTotal = document.forms[0]." + tagFactor.name.substr(0,3) + "IsTotal");
eval("tagPercentageOrDecimal = document.forms[0]." + tagFactor.name.substr(0,3) + "PercentageOrDecimal");
if (tagPercentageOrDecimal.value == "P")
{
reaMax = Math.round((reaMax - 1) * 100);
reaMin = Math.round((1 - reaMin) * 100);
if (parseFloat(tagFactor.value) == 0)
{
alert("Please enter a value other than 0 or leave this field blank.");
f_SetFocus(tagFactor);
return false;
}
if (tagIsTotal.value == "True")
{
if (tagCreditOrDebit.checked)
{
if (parseFloat(tagFactor.value) > reaMin)
{
alert("Please enter a value less than or equal to " + reaMin + "% for a credit or " + reaMax + "% for a debit.");
f_SetFocus(tagFactor);
return false;
}
}
else
{
if (parseFloat(tagFactor.value) > reaMax)
{
alert("Please enter a value less than or equal to " + reaMin + "% for a credit or " + reaMax + "% for a debit.");
f_SetFocus(tagFactor);
return false;
}
}
}
}
return true;
}
EDIT: I think I've figured out why this isn't working as expected, but I still don't know how I can accomplish what I need to. The line below:
if (!document.forms[0].elements[intElement].onblur())
or
if (document.forms[0].elements[intElement].onblur())
is not returning what the single onblur function (f_VerifyRange) is returning. Instead it is always returning either true or false no matter what. In the first case, it returns true and then quits and aborts the submit after the first textbox even though there was no error with the first textbox. In the second case, it returns false and runs through all the boxes. Even though there might have been errors (which it displays), it doesn't think there are any errors, so it continues on with the submit. I guess what I really need is how to get the return value from f_VerifyRange which is my onblur function.
This question is a bit too involved for me at this time of the night, but I will give you this bit of advice:
eval("tagCreditOrDebit = document.forms[0]." + tagFactor.name.substr(0,3) + "CreditOrDebitC");
This can be written in a MUCH better way:
tagCreditOrDebit = document.forms[0][tagFactor.name.substr(0,3) + "CreditOrDebitC"];
In javascript, anywhere where you can use dotted syntax, you can use square brackets.
document.body;
document['body'];
var b = 'body';
document[b];
Also, think about giving your forms some sort of identifier. I have no clue at all why document.forms[0] was the standard way to address a form for so long... if you decide to place another form on the page before this one, then everything will break!
Other ways to do it include:
// HTML
<form name="myFormName">
// Javascript
var f = document.myFormName;
or
<form id="myFormId">
var f = document.getElementById("myFormId")
You´re not getting any success with if (!...onblur()) because the return of onblur() is always undefined when used directly. OnBlur() is a Event Handler Function. Like you descovered, you have to create a workaround.
I ended up solving this with a global variable. I originally set a value g_bHardEditsPassed to true assuming we will have no errors. Then in f_VerifyRange, everytime I return a value, I put a line before it to set the g_bHardEditsPassed variable to match. Then I modified the loop to look like this...
g_bHardEditsPassed = true;
for (var intElement = 0; intElement < document.forms[0].elements.length; intElement = intElement + 1)
{
if (document.forms[0].elements[intElement].name.substr(3) == "FactorAmount")
{
document.forms[0].elements[intElement].onblur()
if (!g_bHardEditsPassed)
{
g_bHardEditsPassed = true;
return false;
}
}
}
return true;
Thanks for everyone's suggestions. I'm sure that the jQuery thing especially will be worth looking into for the future.
First, for the love of god and all that is holy, stop writing native javascript and help yourself to some of that jQuery :)
Second, start using a validation framework. For jQuery, jQuery Validate usually works really well. It supports things like dependencies between different fields, etc. And you can also quite easily add new rules, like valid ISBN numbers, etc.
Edit: As for your code, I'm not sure that you can use onunload for this, as at that point there's no way back, you can't abort at that point. You should put this code on the onsubmit event instead.

Categories

Resources