Multiple if statements and then else Javascript [closed] - javascript

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I'm trying to create a calculator in javascript for inverse trigonometry functions (arcsine, arccosine, arctangent) and I have it so there are checkboxes for each input so window.alert doesn't return NULL (user-friendly).
The Form:
<form name="inverse">
<legend>Legend is here.</legend>
<input type="checkbox" name="inverse-cb1" value="sine"></input><label> sin<sup>-1</sup> ( </label><input type="text" size=5 name="sin"><label> )</label><br>
<input type="checkbox" name="inverse-cb2" value="cosine"></input><label> cos<sup>-1</sup> ( </label><input type="text" size=5 name="cos"><label> )</label><br>
<input type="checkbox" name="inverse-cb3" value="tangent"></input><label> tan<sup>-1</sup> ( </label><input type="text" size=5 name="tan"><label> )</label><br>
<br><input type="button" onclick="trigI()" value="Calculate">
</form>
The script:
function trigI(){
var sin = document.inverse.sin.value; //sine
var cos = document.inverse.cos.value; //cosine
var tan = document.inverse.tan.value; //tangent
var sin1 = Math.asin(sin); //arcsine
var cos1 = Math.acos(cos); //arccosine
var tan1 = Math.atan(tan); //arctangent
var sin1d = sin1 * (180/Math.PI); //convert radians to degrees (sine)
var cos1d = cos1 * (180/Math.PI); //convert radians to degrees (cosine)
var tan1d = tan1 * (180/Math.PI); //convert radians to degrees (tangent)
if (isNaN(sin) || isNaN(cos) || isNaN(tan) ){
window.alert("Please input a number.");
return;
}
if (!document.inverse.inverse-cb1.checked){ //no sine input
window.alert("When cos(\u2220) = " + cos + " and tan(\u2220) = " + tan + " :" + "\n\n" + "cos\u2212\u00B2(A) = " + cos1d + "\n" + "tan\u2212\u00B2(A) = " + tan1d + "\u00B0");
return;
}
if (!document.inverse.inverse-cb2.checked){ //no cosine input
window.alert("When sin(\u2220) = " + sin + " and tan(\u2220) = " + tan + " :" + "\n\n" + "sin\u2212\u00B2(A) = " + sin1d + "\u00B0" + "\n" + "tan\u2212\u00B2(A) = " + tan1d + "\u00B0");
return;
}
if (!document.inverse.inverse-cb3.checked){ //no tangent input
window.alert("When sin(\u2220) = " + sin + " and cos(\u2220) = " + cos + " :" + "\n\n" + "sin\u2212\u00B2(A) = " + sin1d + "\u00B0" + "\n" + "cos\u2212\u00B2(A) = " + cos1d + "\u00B0");
return;
}
if (!document.inverse.inverse-cb1.checked && !document.inverse.inverse-cb2.checked){ //no sine and cosine input
window.alert("When tan(\u2220) = " + tan + " :" + "\n\n" + "tan\u2212\u00B2(A) = " + tan1d + "\u00B0");
return;
}
if (!document.inverse.inverse-cb2.checked && !document.inverse.inverse-cb3.checked){ //no cosine and tangent input
window.alert("When sin(\u2220) = " + sin + " :" + "\n\n" + "sin\u2212\u00B2(A) = " + sin1d + "\u00B0");
return;
}
if (!document.inverse.inverse-cb1.checked && !document.inverse.inverse-cb3.checked){ //no sine and tangent input
window.alert("When cos(\u2220) = " + cos + " :" + "\n\n" + "cos\u2212\u00B2(A) = " + cos1d + "\u00B0");
return;
}
if (!document.inverse.inverse-cb1.checked && !document.inverse.inverse-cb2.checked && !document.inverse.inverse-cb3.checked){ //no input or checked boxes
window.alert("Please input a number or check the correct boxes.");
return;
}
else {
window.alert("When sin(\u2220) = " + sin + ", cos(\u2220) = " + cos + ", and tan(\u2220) = " + tan + " :" + "\n\n" + "sin\u2212\u00B2(A) = " + sin1d + "\u00B0" + "\n" + "cos\u2212\u00B2(A) = " + cos1d + "\u00B0" + "\n" + "tan\u2212\u00B2(A) = " + tan1d + "\u00B0");
return;
}
}
The Question: The multiple if statements are not working so the function never returns. How can it be made to check to conditions of the input and respond in the proper way?

I can't tell you what to do to make it "work", since your desired result is pretty unclear, but a number of problems in your code jumped out at me as I skimmed it top to bottom. Some will still run but give results you aren't expecting, but at least one problem will cause an error and stop the function running. So:
Most of your comments are either redundant and could be removed, or could be made redundant and removed if you made your variable names more descriptive.
The statement
if (isNaN(document.inverse.sin.value) == true || ...)
could be made simpler because you've already declared a variable sin that is equal to document.inverse.sin.value and the == true part is redundant. Just say
if (isNan(sin) || isNan(cos) || isNan(tan)) {
All of your "reset" statements like var sin = null; are both wrong and pointless because (a) using var means you are attempting to redeclare the variables (I think JS just ignores this), so you should just say sin = null;, but in any case (b) they're local variables within your trigI() function so they're all about to disappear anyway when the function returns. If you are trying to clear the fields on the screen you need to say document.inverse.sin.value = "";, but you don't want to annoy the user by clearing all the fields just because one of them was invalid. Tell them which field had a problem, set focus to that field, and let them correct it themselves.
Most of your if statement test something like this:
if (document.inverse-cb1.checked == 'false'){
Which will never be true because you are comparing the .checked property that is a boolean equal to true or false with the string 'false'. You need to say
if (document.inverse-cb1.checked == false){ // note: no quotes
// OR, even better
if (!document.inverse-cb1.checked){
What is sup.sup() supposed to do? sup is a variable that you've set to -1. sup() is a non-existent function that in any case you shouldn't be trying to call as a method of a number. Fix this first, because I think this is what is stopping the function returning.
EDIT: I noticed another big problem:
document.inverse.inverse-cb1.checked
You can't use the "dot" object notation for properties that don't follow the rules for JS identifier naming, and JS identifiers can't have a "-" in them. So although "inverse-cb1" is a valid property name you have to use the array-style bracket [] syntax to access it:
document.inverse["inverse-cb1"].checked
Or you could just remove the "-" from both the html and your JS.

Related

How to split innherHTML string using Javascript into specific parts after a certain character like a '+' sign

I need to break a string apart after certain characters.
document.getElementById("result").innerHTML = Monster + "<p id='vault" + loop + "'> || HP: " + HP + "</p>" + " || Defense: " + Def + " || Attack: " + ATK + " || Can it Dodge/Block: " + DB + " || Can it retaliate: " + RET + " || Initative: " + INT + " || Exp: " + MEXP + " <input type='submit' class='new' onclick='Combat(" + loop + ")' value='FIGHT!'></input>" + "<br><br>" + A;
function Chest(id){
window.open('LootGen.html', '_blank');
}
function Combat(id){
document.getElementById("C").value = document.getElementById("vault" + id).innerHTML;
}
When this runs the value that results is:
|+HP:+20
However I only want '20' part,now keep in mind that this variable does change and so I need to use substrings to somehow pull that second number after the +. I've seen this done with:
var parameters = location.search.substring(1).split("&");
This doesn't work here for some reason as first of all the var is an innher html.
Could someone please point me in the write direction as I'm not very good at reading docs.
var text = "|+HP:+20";
// Break string into an array of strings and grab last element
var results = text.split('+').pop();
References:
split()
pop()
using a combination of substring and lastIndexOf will allow you to get the substring from the last spot of the occurrence of the "+".
Note the + 1 moves the index to exclude the "+" character. To include it you would need to remove the + 1
function Combat(id){
var vaultInner = document.getElementById("vault" + id).innerHTML;
document.getElementById("C").value = vaultInner.substring(vaultInner.lastIndexOf("+") + 1);
}
the code example using the split would give you an array of stuff separated by the plus
function Combat(id){
//splits into an array
var vaultInner = document.getElementById("vault" + id).innerHTML.split("+");
//returns last element
document.getElementById("C").value = vaultInner[vaultInner.length -1];
}

How to return a value in the only non-blank column in a range for sendEmail function in Google App Scripts

The issue is: I can't find a way to return the value for 'Course' because each form submission generates a new row where the name of the course is spread over columns E to M (column 4 through 12).
In each row, there is only one 'Course' name in one of the columns from E to M (e.g only in F) and all other columns are blank. (Users can only select one course and all the other columns will be blank. I have to categorize the courses into the 9 columns because of the page breaks in order to split the sheer number of options that users select the course from.) How do I return the value of the only non blank cell from E to M which will be entered in the email ?
I was advised to insert the entire findCourse function inside of the sendEmail function before any of the other code. I did so but I have still been receiving failure notifications of the Google App Scripts: TypeError: Cannot read property "values" from undefined. (line 14, file "Code") (referring to var value = e.values[i])
The full code below:
function sendEmail(e) {
function findCourse (e){
var courseToTake;
//loop through values
for ( var i = 4; i <=12; i ++){
//pull value into variable
var value = e.values[i];
if (value != undefined){
//if we find an actual string value, set the course to take variable
courseToTake = value;
}
}
return courseToTake;
}
var Name = e.namedValues["Full name as appear in NRIC"];
var Course = findCourse();
var Start = e.values[14];
var End = e.values[15];
var StartTime = e.values[24];
var EndTime = e.values[25];
var Details = e.values[13];
var Cost = e.values[17];
var Email = e.values[18];
var ROname = e.values[19];
var ROemail = e.values[20];
var Location = e.values[23];
var subject = "Training Approval Request for " + Course;
var message = "<p >" + "Dear " + ROname + "<p />"
+ Name + " seeks your approval to attend the " + Course + ". The details are as follow:"
+ "<p >" + "<b>Date:</b> " + Start + " - " + End + " <br />"
+ "<b>Time:</b> " + StartTime + " - " + EndTime + " <br />"
+ "<b>Location:</b> " + Location + " <br />"
+ "<b>Course objectives and benefits:</b> " + Details + " <br />"
+ "<b>Course fees:</b> " + "$" + Cost + " <br />" + "<p />"
+ "Please reply directly to this email for your approval or if you have any questions/comments. Thank you. "
MailApp.sendEmail(ROemail, Email, subject, message);
}
After rearranging findCourse as its own function: sorry if I made any mistakes here but i'll try my best to follow all suggestions. If i've added in Logger.log(e) correctly, both functions seem to be undefined
function sendEmail(e) {
Logger.log(e);
var Name = e.values[2];
var Course = findCourse();
var Start = e.values[14];
var End = e.values[15];
var StartTime = e.values[24];
var EndTime = e.values[25];
var Details = e.values[13];
var Cost = e.values[17];
var Email = e.values[18];
var ROname = e.values[19];
var ROemail = e.values[20];
var Location = e.values[23];
var subject = "Training Approval Request for " + Course;
var message = "<p >" + "Dear " + ROname + "<p />"
+ Name + " seeks your approval to attend the " + Course + ". The details are as follow:"
+ "<p >" + "<b>Date:</b> " + Start + " - " + End + " <br />"
+ "<b>Time:</b> " + StartTime + " - " + EndTime + " <br />"
+ "<b>Location:</b> " + Location + " <br />"
+ "<b>Course objectives and benefits:</b> " + Details + " <br />"
+ "<b>Course fees:</b> " + "$" + Cost + " <br />" + "<p />"
+ "Please reply directly to this email for your approval or if you have any questions/comments. Thank you. "
MailApp.sendEmail(ROemail, Email, subject, message);
}
function findCourse (e){
var courseToTake;
//loop through values
for ( var i = 4; i <=12; i ++){
//pull value into variable
var value = e.values[i];
if (value != undefined){
//if we find an actual string value, set the course to take variable
courseToTake = value;
}
}
return courseToTake;
var courseToTake = findCourse(e);
Logger.log(e);
}
I will really deeply appreciate any help or alternative solutions here.
Thank you!
What I changed in your code to address your question:
I assigned the onFormSubmit trigger to your sendEmail function so the event object would no longer be undefined
I added a call to findCourse() so your course variable would no longer be undefined
I fixed the undefined check by changing if(value != undefined) to if(typeof value !== 'undefined')
I added a check for a blank value (This was the important bit in the logic after the faulty undefined check) if(value != '')
Explanation:
To trigger the event, an installable trigger needs to be setup for the On Form Submit event that points to your sendEmail function. This can be found in Resources -> Current Project Triggers
To retrieve the course, you need to call your function findCourse() and pass in the e event object. Example: var course = findCourse(e);. This will assign the return value from findCourse(e); to the course variable. You can then use this variable like normal within the rest of your statements.
When checking for undefined, you need to use typeof and then check for the string of 'undefined', or your check will ironically throw an undefined exception.
The values of the form submit should not be undefined, blank values should just be blank strings. so checking for non-blank strings was necessary to get the course name from the values array.
Fixed Code:
function sendEmail(e) {
Logger.log(e)
var course = findCourse(e);
var Name = e.values[19];
var Start = e.values[12];
var End = e.values[14];
var StartTime = e.values[13];
var EndTime = e.values[15];
var Details = e.values[11];
var Cost = e.values[17];
var Email = e.values[20];
var ROname = e.values[21];
var ROemail = e.values[22];
var Location = e.values[16];
var subject = "Training Approval Request for " + course;
var message = "<p >" + "Dear " + ROname + "<p />"
+ Name + " seeks your approval to attend the " + course + ". The details are as follow:"
+ "<p >" + "<b>Date:</b> " + Start + " - " + End + " <br />"
+ "<b>Time:</b> " + StartTime + " - " + EndTime + " <br />"
+ "<b>Location:</b> " + Location + " <br />"
+ "<b>Course objectives and benefits:</b> " + Details + " <br />"
+ "<b>Course fees:</b> " + "$" + Cost + " <br />" + "<p />"
+ "Please reply directly to this email for your approval or if you have any questions/comments. Thank you. "
MailApp.sendEmail(ROemail, Email+";" + "redactedEmail", subject, message);
}
function findCourse (e){
var courseToTake;
//loop through values
for ( var i = 2; i <=10; i ++){
//pull value into variable
var value = e.values[i];
if (typeof value !== 'undefined'){ //If value is defined
if(value != ''){ //If value is not blank
//if we find an actual non-blank string value, set the course to take variable
courseToTake = value;
}
}
}
return courseToTake;
}

How do I copy (or even having a button to select it all) a document.getelementbyid output field in html?

I'm trying to essentially set up a button that will either copy a bunch of text that will get output to a document.getelementbyid output to help me out while at work. This is what I have so far for the output and everything works, but would love to have a button that will automatically highlight everything taken from all my input fields.
function display(){
var caller = document.getElementById("form1").value;
var ctn = document.getElementById("form2").value;
var fan = document.getElementById("form3").value;
var business = document.getElementById("form4").value;
var requestor = document.getElementById("form5").value;
var reason = document.getElementById("form6").value;
document.getElementById("output").innerHTML = "form1: " + form1 + "<br>form2: " + form2 + "<br>form3: " + form3 + "<br>form4: " + form4 + "<br>form5: " + form5 + "<br>form6: " + form6;
}
This feeds data from my input fields at the top (naturally they have different names and labels in the document, just can't copy anything proprietary here). The below codes are the button code and the paragraph code to display it when I click so that it appears on the page for me to select.
<button onclick="display();" style="width: 50px; background-color:#3ea055">Submit</button>
<p id="output"></p>
I've tried several different snippets of code online to get it to either select or copy or whatever, and it isn't working.
you dont have variables named form1 form2 etc., in the output area I've changed the values to your variable names try this
function display(){
var caller = document.getElementById("form1").value;
var ctn = document.getElementById("form2").value;
var fan = document.getElementById("form3").value;
var business = document.getElementById("form4").value;
var requestor = document.getElementById("form5").value;
var reason = document.getElementById("form6").value;
document.getElementById("output").innerHTML = "form1: " + caller + "<br>form2: " + ctn + "<br>form3: " + fan + "<br>form4: " + form4 + "<br>form5: " + requestor + "<br>form6: " + form6;
}
In the line where you print the values to the output element you need to use the variables you just filled.
document.getElementById("output").innerHTML = "form1: " + caller + "<br>form2: " + ctn+ "<br>form3: " + fan + "<br>form4: " + business + "<br>form5: " + requestor + "<br>form6: " + reason;

Leading zeros from PDF field to javascript variable

Hopefully this is the correct place to ask this question. I'm pretty much brand new to javascript, but seeing it's similarities to the other languages I write in, it's been pretty easy so far- until now.
I'm writing a script for a button that is clicked when a user is done filling out a grid. The script goes through the fields in the grid, grabs the information, and generates an email. It then sends out a mailto: command with the information that was generated, much easier than the user having to type the email themselves. The problem I'm having is that one of the criteria for a field is a Tax ID, which can sometimes start with a zero, and when I go to assign that field value to a variable, it drops the leading zero. How do I get javascript to keep this leading zero? I've tried declaring a variable with a " " at the beginning to try to force it to recognize the variable as a string, but that doesn't seem to work.
Here's my code:
if(this.getField("ProviderOne").value != "")
{
// This is the form return email. Its hardcoded
// so that the form is always returned to the same address
var cToAddr = "blank#blank.org";
// First, get the client CC email address
var cCCAddr = "blank#blank.com";
var pOneTaxID = new String(this.getField("ProviderOneTaxID").value); //tring to force string value
// Set the subject and body text for the email message
var ProviderOne = this.getField("ProviderOne").value + " NPI:" + this.getField("ProviderOneNPI").value + " Tax ID:" + pOneTaxID;
var ProviderTwo = this.getField("ProviderTwo").value + " NPI:" + this.getField("ProviderTwoNPI").value + " Tax ID:" + this.getField("ProviderTwoTaxID").value;
var ProviderThree = this.getField("ProviderThree").value + " NPI:" + this.getField("ProviderThreeNPI").value + " Tax ID:" + this.getField("ProviderThreeTaxID").value;
var ProviderFour = this.getField("ProviderFour").value + " NPI:" + this.getField("ProviderFourNPI").value + " Tax ID:" + this.getField("ProviderFourTaxID").value;
var ProviderFive = this.getField("ProviderFive").value + " NPI:" + this.getField("ProviderFiveNPI").value + " Tax ID:" + this.getField("ProviderFiveTaxID").value;
var cSubLine = this.getField("ProviderOne").value + " ERA setup for [BLANK]";
var cBody = "To [BLANK], \n \nPlease enroll the following providers to receive [BLANK] through [BLANK] under [BLANK]: \n \n";
if(this.getField("ProviderOne").value != "")
cBody += "1. " + ProviderOne + "\n";
if(this.getField("ProviderTwo").value != "")
cBody += "2. " + ProviderTwo + "\n";
if(this.getField("ProviderThree").value != "")
cBody += "3. " + ProviderThree + "\n";
if(this.getField("ProviderFour").value != "")
cBody += "4. " + ProviderFour + "\n";
if(this.getField("ProviderFive").value != "")
cBody += "4. " + ProviderFive + "\n";
cBody += "\n Thank you,\n" + this.getField("ProviderOne").value;
app.mailMsg({bUI: true, cTo: cToAddr, cCc: cCCAddr, cBCc: "", cSubject: cSubLine, cMsg: cBody});
}
else
{
app.alert("Please enter at least one payer into the grid above.", 1, 0, "Unfilled Form");
this.getField("ProviderOne").setFocus();
}
Thanks a ton for taking the time to read through this, and even more thanks to you if you can help me find a solution.
-Andrew
Figured it out. Instead of grabbing the value using getField("FieldName").value, I grabbed it using .valueAsString. Hopefully this is useful if someone finds it down the road.

Assigning array value not working?

For a chess game I search for possible attackers on an enemy piece.
Board representation is done via a multi-dimensional array. board[i][j], where i = row and j is column (so 8x8) and the value is the piece itself.
When searching for possible attackers I want to create a new array aPossibleAttackers[i][j]
var aPossibleAttackers = []; // create array
var ti,tj; // temp row/col
I do a search in all possible directions (0-7) and look for the first piece I meet. So direction and distance are known then. Then I calculate which field this is and want to copy the correspondending value from board[i][j] to aPossibleAttackers[i][j]. It's not working, though.
Code:
alert( veld(attackerRow,attackerCol) + " pos att op veld " + veld((attackerRow + (i * rowStep)), (attackerCol + (i * colStep))));
aPossibleAttackers[search_dir] = i; // searchdirection and distance, OK
ti = attackerRow + (i * rowStep); // OK
tj = attackerCol + (i * colStep); // OK
//aPossibleAttackers[ti][tj] = board[ti][tj]; // not possible????
alert("test2 ti= " + ti + " tj=" + tj + " ?? " + aPossibleAttackers);
What am I doing wrong?? board[i][j] does exist, or else I would not have found a piece.
could be a string casting issue
try
alert(
veld(attackerRow,attackerCol)
+ " pos att op veld "
+ veld(((attackerRow*1) + (i * rowStep)), ((attackerCol*1) + (i * colStep))));
aPossibleAttackers[search_dir] = i; // searchdirection and distance, OK
ti = (attackerRow*1) + (i * rowStep); // OK
tj = (attackerCol*1) + (i * colStep); // OK
//aPossibleAttackers[ti][tj] = board[ti][tj]; // not possible????
alert("test2 ti= " + ti + " tj=" + tj + " ?? " + aPossibleAttackers);
just a guess

Categories