COMPLETE - pureJS issue with writing data, any ideas? - javascript

I am trying to take the data from "create_name()" and write the outcome to the
<p id="name"> </p>
updating the variable name to show the new version.
however I am a bit lost in honesty and instead it returns "undefined" as the name.
the code obviously gets to this part and then fails:
Writedata(create_name); // now write our username
menu_function();
}
function Writedata(nameUser){
document.getElementById("name").innerHTML='hello ' + nameUser + ' below are your options'; // write the username.
}
You can see the code for the entire section I am trying to make work here.
I hope I explained clearly enough.
Any Questions? feel free to ask, all help is appreciated!
init(); // lets start the inital func
function init(){ // Do some asking shit
var name = prompt('hello, what is your name?'); // ask for the name
document.write('<p id="name">hello ' + name + ' </p>');
document.write('<p id="user" >1 - create a username</p>');
document.write('<p id ="play" >2 - Play Quiz<p>');
document.write('<p id="reload">3 - quit and reload<p>');
Writedata(name); // tell our witer to write the name
}
function menu_function() {
var choice = prompt("hello " + name + " please select an option from the list to your left");
switch (choice) {
case "1": opt1_function(); break;
case "2": opt2_function(); break;
case "3": reload_method(); break;
default: menu_function(); break;
}
}
menu_function();
function opt1_function() {
alert(name + " you have selected option 1");
create_name();
}
function create_name() {
var forename = prompt("what is your forename?");
var surname = prompt("what is your surname?");
var username = alert("hello " + forename + " " + surname);
var string1 = forename.substring(0 , 1);
var create_name = alert(string1 + surname);
Writedata(create_name); // now write our username
menu_function();
}
function Writedata(nameUser){
document.getElementById("name").innerHTML='hello ' + nameUser + ' below are your options'; // write the username.
}

stop assigning alert() function return values to variables, alert() has no return value look at this alert definition
change this line
var create_name = alert(string1 + surname);
to
alert(string1 + surname);
var create_name = string1 + surname;

Changed the data within the create_name() function to this:
function create_name() {
var forename = prompt("what is your forename?");
var surname = prompt("what is your surname?");
var username = alert("hello " + forename + " " + surname);
var string1 = forename.substring(0 , 1);
var create_name = string1 + surname;
Writedata(create_name); // now write our username
menu_function();
}
function Writedata(nameUser){
document.getElementById("name").innerHTML='hello ' + nameUser + ' below are your options'; // write the username.
}
and now it works!

Related

How do I make the boolean produce false for canCode?

I am wondering how I can call the summarizeUser function and make the canCode part log to the console as false?
Thank you in advance.
var name = 'Maya';
var age = 24;
var canCode = true;
function summarizeUser(userName, userAge, userHasHobby){
return(
`Name is ${name}, age is ${age}, can code = ${canCode}`
);
}
console.log(summarizeUser('Maya', 24, canCode));
var name = 'Maya';
var age = 24;
var canCode = true;
function summarizeUser(userName, userAge, userHasHobby){
canCode=false;
console.log( `Name is ${name}, age is ${age}, can code = ${canCode}`);
}
summarizeUser(name,age,canCode);
console.log(canCode);
I'm not really sure that I understood what you want to do. If I understood it right, then your code does not make sense ;-)
var name = 'Maya';
var age = 24;
var canCode = true;
function summarizeUser(userName, userAge, userHasHobby){
console.log( 'Name is ' + userName + ', age is ' + userAge + ', canCode = ' + userHasHobby);
// if you want to write false if user has a hobby, then you can do the following:
console.log( 'Name is ' + userName + ', age is ' + userAge + ', canCode = ' + !userHasHobby);
}
summarizeUser(name,age,canCode);
Easy, set canCode=false in the function and log it out.

Javascript Onclick Function not working when Toggling Temperature

I'm working on a weather api and I'm having trouble toggling between Celsius and Fahrenheit.
I used a separate function to get the location as well as call from the API.
I also added an onclick function within this second function. I can get it to toggle to one temperature but not back.
function getTemp(data) {
// API variables
var temp1 = data.main.temp;
var weatherUrl = data.weather[0].icon;
var tempInC = Math.round(temp1); // Temp in Celsius
var tempInF = Math.round(temp1 * 9/5 +32)
// Inner HTML variables
var weatherF = "The weather is " + tempInF + " ℉ <br>" +
"<img src='" + weatherUrl + "'/>";
var weatherC = "The weather is " + tempInC + " ℃ <br>" +
"<img src='" + weatherUrl + "'/>";
// Button DOM variables
var buttonText = document.getElementsByTagName("button")[0].innerText;
var buttonId = document.getElementById('btn');
x.innerHTML = weatherF;
buttonId.onclick = function toggleTemp() {
if(buttonText == "Convert to Celsius") {
x.innerHTML = weatherC;
buttonId.innerText = "Convert to Fahrenheit";
} else {
x.innerHTML = weatherF;
buttonId.innerText = "Convert to Celsius";
}
}
}
I used innerText because I thought it was the easiest way to toggle back and forth between temp. I can get the weather to convert to Celsius, but the else statement is not working. Fyi, I was not able to get the button text to change using the tag name which is why I resorted to using an id in the button click function. I'm still pretty new at Javascript. Any help would be appreciated.
You need to update the buttonText variable when you toggle the text of buttonId.
buttonId.onclick = function toggleTemp() {
if (buttonText == "Convert to Celsius") {
x.innerHTML = weatherC;
buttonText = buttonId.innerText = "Convert to Fahrenheit";
} else {
x.innerHTML = weatherF;
buttonText = buttonId.innerText = "Convert to Celsius";
}
}
Your variable x is undefined. In the future, try to avoid using the innerHTML property, which can break event listeners and be slow to render.
Neither buttonText nor x are defined in the scope of your onclick function, which might be why nothing happens. Have you checked the console for errors?
function getTemp(data) {
// API variables
var temp1 = data.main.temp;
var weatherUrl = data.weather[0].icon;
var tempInC = Math.round(temp1); // Temp in Celsius
var tempInF = Math.round(temp1 * 9/5 +32)
// Inner HTML variables
var weatherF = "The weather is " + tempInF + " ℉ <br>" +
"<img src='" + weatherUrl + "'/>";
var weatherC = "The weather is " + tempInC + " ℃ <br>" +
"<img src='" + weatherUrl + "'/>";
// Button DOM variables
var x = ...; // Declare x for the function scope here
var buttonText = document.getElementsByTagName("button")[0].innerText;
var buttonId = document.getElementById('btn');
x.innerHTML = weatherF;
buttonId.onclick = (function (x, wC, wF, btn) {
return function () {
// Change DOM
if(btn.innerText == "Convert to Celsius") {
x.innerHTML = wC;
btn.innerText = "Convert to Fahrenheit";
} else {
x.innerHTML = wF;
btn.innerText = "Convert to Celsius";
}
};
})(x, weatherC, weatherF, document.getElementsByTagName("button")[0])
}

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

go to the next index of an array using onclick in Javascript

I apologize in advance if I'm vague or my code is difficult to understand, I'm still learning this stuff. I'm trying to display information that is stored within an array. I want to display this information when a button is clicked and when it is clicked again, the next index in the array displays its information..
I need help setting up a function that advances to the next index of the array. Thanks!
(function(){
var students =[ //array of information
{name:'john',
address:{
address:'821 Imaginary St',
city:'Chicago',
state:'Il'},
gpa:[4.0,3.5,3.8]},
{name:'jim',
address:{
address:'127 fake Rd',
city:'Orlando',
state:'Fl'},
gpa:[2.5,3.3,3.6]}];
var redBut = document.querySelector('.buttonred');
redBut.onclick = getInfo;
var count = 0;
function getInfo(){
var stn = students[0];
if(count<3){
count++;
document.getElementById('name').innerHTML = 'Name: ' + stn.name; //this is what is to be displayed when the button is clicked
document.getElementById('address').innerHTML = 'Address: ' + stn.address.address + " " + stn.address.city + ", " + stn.address.state;
document.getElementById('gpa').innerHTML = 'GPA: ' + stn.gpa[0] +", " + stn.gpa[1] + ", " + stn.gpa[2];
document.getElementById('date').innerHTML = 'Date: ' + d.toLocaleDateString();
document.getElementById('gpaavg').innerHTML = 'Average GPA: ' + gpas;
}
}
I think you want: var stn = students[count];
And not: var stn = students[0];
(DOH!)

Appending variables to a string in javascript

I am using prototype in my application but I am not sure how to add this correctly. Basically I have the following function and I need to construct the href of an anchor from which I already have the reference to a series of appended values
MyJavascriptClass.prototype.init = function() {
this.ToDate = $(this.Prefix + 'ToDate');
this.FromDate = $(this.Prefix + 'FromDate');
}
so in the following function I need to add those as parameters in the url attribute
MyJavascriptClass.prototype.btnClicked = function(evt) {
this.lnkShowLink.setAttribute('href', 'MyWebpage.aspx?StartDate=7/18/2012&EndDate=1/19/2012');
}
How can i do something like 'MyWebPage.aspx?StartDate=this.ToDate&EndDate=this.FromDate' ? Any help would be appreciated.
If you are using jquery, and $(this.Prefix + 'ToDate') and $(this.Prefix + 'FromDate') represent fields that contain values, then you can do this:
MyJavascriptClass.prototype.btnClicked = function(evt) {
this.lnkShowLink.setAttribute('href', 'MyWebpage.aspx?StartDate=' + this.ToDate.val() + '&EndDate=' + this.FromDate.val() + '');
}
It is difficult to tell from your code what they represent, and why you have them wrapped in $(..).
If ToDate and FromDate contain the two date values, then this should work...
'MyWebPage.aspx?StartDate=' + this.ToDate + '&EndDate=' + this.FromDate
If you don't know every properties:
var properties = [];
for(var i in this)
if(this.hasOwnProperty(i))
properties.push(i+'='+this[i]);
var url = 'MyWebPage.aspx?'+properties.join('&');
var string = "My name is: ",
name = "Bob",
punctuation = ".",
greeting = string + name + punctuation;
Or
var User = { name : "Bob", age : 32, sign : "Leo" },
welcome = "Hi, I'm " + User.name + ", and I'm " + User.age + " years old, I'm a " + User.sign + ", and I enjoy long walks on the beach.";

Categories