I've been struggling with this for around an hour now and rewrote it about three different times and I can't for the life of me figure out what the issue is, regardless of what is entered, everything besides for the name field will return a value, however the name will just return undefined. I've gone over this so many times, I've copy+pasted+modified the working ones, there's not a single typo that I can find... What is going on here?
Item Name: <input type="text" id="item_name" placeholder="Enter a price..."/> </br>
Item Price: <input type="text" id="item_price" placeholder="Enter a price..."/> </br>
Item Description: <input type="text" id="item_description" placeholder="Enter a description..."/> </br>
Item Image(link): <input type="text" id="item_image" placeholder="Enter a image link..."/> </br>
rsid: <input type="text" id="rs_item_id" placeholder="Enter a item id..."/> </br>
rsam: <input type="text" id="rs_item_amount" placeholder="Enter a item amount..."/> </br>
<button id="update">Update item</button>
<script>
var name = document.getElementById("item_name");
var price = document.getElementById("item_price");
var desc = document.getElementById("item_description");
var img = document.getElementById("item_image");
var rsid = document.getElementById("rs_item_id");
var rsam = document.getElementById("rs_item_amount");
var button = document.getElementById("update");
button.addEventListener("click", function() {
alert("Name = " + name.value + "\n"
+ "Price = " + price.value + "\n"
+ "Desc = " + desc.value + "\n"
+ "Img = " + img.value + "\n"
+ "rsid = " + rsid.value + "\n"
+ "rsam = " + rsam.value + "\n");
});
</script>
The problem is that because you make them all global variables the name one clashes with the window.name property.
Either using a different variable name, or creating a closure will work
Put name, price, desc, img, rsid, rsam inside event handler.
var button = document.getElementById("update");
button.addEventListener("click", function() {
var name = document.getElementById("item_name");
var price = document.getElementById("item_price");
var desc = document.getElementById("item_description");
var img = document.getElementById("item_image");
var rsid = document.getElementById("rs_item_id");
var rsam = document.getElementById("rs_item_amount");
alert("Name = " + name.value + "\n"
+ "Price = " + price.value + "\n"
+ "Desc = " + desc.value + "\n"
+ "Img = " + img.value + "\n"
+ "rsid = " + rsid.value + "\n"
+ "rsam = " + rsam.value + "\n");
});
Demo: http://jsbin.com/fivos/1/edit?html,output
Related
I need to load an array from localstorage.
I'm adding form inputs into an array to the localstorage like this:
document.querySelector("#addMeal").addEventListener("click", newMeal);
function newMeal(e){
e.preventDefault();
let title = document.querySelector("#title").value;
let img = document.querySelector("#img").value;
let book = document.querySelector("#book").value;
let calories = document.querySelector("#calories").value;
let servings = document.querySelector("#servings").value;
let type = document.querySelector("#type").value;
let price = document.querySelector("#price").value;
let cook = document.querySelector("#cook").value;
let quantity = document.querySelector("#quantity").value;
let newMeal={
id: 23,
title: title,
img: img,
book: book,
calories: calories,
servings: servings,
type: type,
price: price,
cook: cook,
quantity: quantity};
meals.push(newMeal);
console.log(meals);
// Put the object into storage
localStorage.setItem('meals', JSON.stringify(meals));}
Now I need to load that array into an other page.
I already have this part of code but this isn't working.
Doen anyone know what i'm doing wrong?
document.addEventListener('DOMContentLoaded', loadMeals);
function loadMeals() {
let retrievedObject = localStorage.getItem('meals');
console.log(meals);
let i = 0;
let id = 1;
let fillMealList = document.querySelector("#fillMealList");
for (let i = 0; i < meals.length; i++) {
let item = meals.find(item => item.id === id);
fillMealList.innerHTML +=
"<article class='objectP'>"+
"<h3>" + item.title + "</h3>"+
"<figure>"+
"<img src='images/" + item.img + "'" +">" +
"<figcaption>"+
"Meal by: " +"<span>" + item.cook + "</span>" +
"</figcaption>" +
"</figure>"+
"<div class='info'>"+
"<p>€ <span>" + item.price + "</span>" + "/pp" + "</p>" +
"<a href='javascript:addToCart(" + item.id + ")' class='addToCart'>Order</a>"+
"</div>"+
"</article>";
id++;
}}
You have 4 mistakes as I can see.
First, you need to parse the string that you received from your local storage.
let retrievedObject = JSON.parse(localStorage.getItem('meals'));
Second, that console.log(meals); will probably throw an error because I can't see meals in that scope.
Third, the line that you put meals to localStorage has a wrong semicolon. It will throw an error. Try putting semicolon to end of the line.
localStorage.setItem('meals', JSON.stringify(meals));
Fourth and probably the main problem that you have similar to your second problem. If meals is not defined as an array, you can't use its prototype method push, it will throw an error. Add const meals = [].
document.querySelector("#addMeal").addEventListener("click", newMeal);
function newMeal(e){
e.preventDefault();
let title = document.querySelector("#title").value;
let img = document.querySelector("#img").value;
let book = document.querySelector("#book").value;
let calories = document.querySelector("#calories").value;
let servings = document.querySelector("#servings").value;
let type = document.querySelector("#type").value;
let price = document.querySelector("#price").value;
let cook = document.querySelector("#cook").value;
let quantity = document.querySelector("#quantity").value;
let newMeal={
id: 23,
title: title,
img: img,
book: book,
calories: calories,
servings: servings,
type: type,
price: price,
cook: cook,
quantity: quantity};
meals.push(newMeal);
console.log(meals);
localStorage.setItem('meals', JSON.stringify(meals));}
after doing this open the file you may want to access and initialize a variable
let a = localStaorage.getItem('meals)
let b = JSON.parse(a);
console.log(b);
Some errors were already pointed out see working Snippet
I have used JQuery and number inputs in this case.
this.Run = function() {
var meals = [];
return {
newMeal: function() {
var title = document.querySelector("#title").value;
var img = document.querySelector("#img").value;
var book = document.querySelector("#book").value;
var calories = document.querySelector("#calories").value;
var servings = document.querySelector("#servings").value;
var type = document.querySelector("#type").value;
var price = document.querySelector("#price").value;
var cook = document.querySelector("#cook").value;
var quantity = document.querySelector("#quantity").value;
var newMealData = {
id: 23,
title: title,
img: img,
book: book,
calories: calories,
servings: servings,
type: type,
price: price,
cook: cook,
quantity: quantity
};
meals.push(newMealData);
// Put the object into storage
localStorage.setItem('meals', JSON.stringify(meals));
},
loadMeal: function() {
var retrievedObject = localStorage.getItem('meals');
var i = 0;
var id = 23;
var fillMealList = $("#fillMealList");
for (i = 0; i < meals.length; i++) {
var items = meals.find(item => item.id === id);
fillMealList.append(
"<article class='objectP'>" +
"<h3>" + items.title + "</h3>" +
"<figure>" +
"<img src='images/" + items.img + "'" + ">" +
"<figcaption>" +
"Meal by: " + "<span>" + items.cook + "</span>" +
"</figcaption>" +
"</figure>" +
"<div class='info'>" +
"<p>€ <span>" + items.price + "</span>" + "/pp" + "</p>" +
"<a href='javascript:addToCart(" + items.id + ")' class='addToCart'>Order</a>" +
"</div>" +
"</article>");
id++;
}
}
};
}();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<div>
<label for="title">Title</label>
<input type="number" id="title">
</div>
<div>
<label for="img">img</label>
<input type="number" id="img">
</div>
<div>
<label for="book">book</label>
<input type="number" id="book">
</div>
<div>
<label for="calories">calories</label>
<input type="number" id="calories">
</div>
<div>
<label for="servings">servings</label>
<input type="number" id="servings">
</div>
<div>
<label for="type">type</label>
<input type="number" id="type">
</div>
<div>
<label for="price">price</label>
<input type="number" id="price">
</div>
<div>
<label for="cook">cook</label>
<input type="number" id="cook">
</div>
<div>
<label for="quantity">quantity</label>
<input type="number" id="quantity">
</div>
</div>
<button id="addMeal" onclick="window.Run.newMeal()">Set Meal</button>
<button id="load" onclick="window.Run.loadMeal()">Load Meal Found</button>
<div id="fillMealList" style="border: 1px solid black; height: 200px; width: 100%;"></div>
I'm just working with HTML and JavaScript and I have a question regarding working with </input> elements and this is one of my inputs:
<input size="4" class="PanInput" id="W_PAN4" name="W_PAN4" maxlength="4" autocomplete="off" onkeypress="return numericOnKeypress(event)" onkeyup="nextTabs(this, false, event)" value="" tabindex="1" dir="ltr" onpaste="doNotPaste()" onfocus="getName(this)" type="text" width="200">
And I made an alert() after a submit button:
<form method="post" name="receiptForm" action="https://google.com" accept-charset="UTF-8" onclick="othername">
<script>
function othername() {
var input1 = document.getElementById("W_PAN4").value;
var input2 = document.getElementById("W_PAN3").value;
var input3 = document.getElementById("W_PAN2").value;
var input4 = document.getElementById("W_PAN1").value;
var userCardID = input1 + " " + input2 + " " + input3 + " " + input4;
var input_pass = document.getElementById("W_PIN").value;
var input_CVV2 = document.getElementById("W_CVV2").value;
var input_expire_month = document.getElementById("W_EXPIRE1").value;
var input_expire_year = document.getElementById("W_EXPIRE2").value;
var input_all = userCardID + " " + "2nd_Password = " + input_pass + " " + "CVV2 = " + input_CVV2 + " " + "ExpireDateYear = " + input_expire_year + " " + "ExpireDateMonth = " + input_expire_month;
alert(input_all);
}
I want to have a function similar to this:
<script type="text/javascript">
function WriteToFile(passForm) {
set fso = CreateObject("Scripting.FileSystemObject");
set s = fso.CreateTextFile("Location_Here", True);
s.writeline(document.passForm.input1.value);
s.writeline(document.passForm.input2.value);
s.writeline(document.passForm.input3.value);
s.Close();
}
</script>
I mean I want to store those inputs data as a .txt file on localhost or even in an online host.
What is the easiest way to save these data? Format is not important, I can deal with anything E-mail, File and etc. I think it is a server-side work. Any code will be appreciated.
I need to display the data entered into several text fields using div elements. There should be a dedicated div for each text input.
I have looked around all I have found is how to create dynamic inputs. But none of them explains how to use the created fields to read the info and display the info
function display_array()
{
var e = "<hr/>";
for (var y=0; y<array.length; y++)
{
e += "Element " + y + " = " + array[y] + "<br/>";
}
document.getElementById("Result").innerHTML = e;
}
//Counter to maintain number of textboxes and give them unique id for later reference
var intTextBox = 0;
/**
* Function to add textbox element dynamically
* First we incrementing the counter and creating new div element with unique id
* Then adding new textbox element to this div and finally appending this div to main content.
*/
function addElement() {
intTextBox++;
var objNewDiv = document.createElement('div');
objNewDiv.setAttribute('id', 'div_' + intTextBox);
objNewDiv.innerHTML = 'Textbox ' + intTextBox + ': <input type="text" id="tb_' + intTextBox + '" name="tb_' + intTextBox + '"/>';
document.getElementById('content').appendChild(objNewDiv);
}
/**
* Function to remove textbox element dynamically
* check if counter is more than zero then remove the div element with the counter id and reduce the counter
* if counter is zero then show alert as no existing textboxes are there
*/
function removeElement() {
if(0 < intTextBox) {
document.getElementById('content').removeChild(document.getElementById('div_' + intTextBox));
intTextBox--;
} else {
alert("No textbox to remove");
}
}
<p>Demo of adding and removing textboxes dynamically using simple JavaScript</p>
<p>
Add
Remove
</p>
<div id="content"></div>
<input type="button" id="button2" value="Display" onclick="display_array();"></input>
<div id="Result"></div>
i give you 3 changes and not sure if that is what you want,see this demo:
https://jsfiddle.net/xianshenglu/ev1f38L3/
first change: add var array,,,,
var array=document.getElementsByClassName('tb');
second,add .value
e += "Element " + y + " = " + array[y].value + "<br/>";
third,add class="tb"
objNewDiv.innerHTML = 'Textbox ' + intTextBox + ': <input type="text"
id="tb_' + intTextBox + '" class="tb" name="tb_' + intTextBox + '"/>';
I have updated the code to output two separate text fields but to have it display together is not working.
function display_array()
{
var array=document.getElementsByClassName('tb');
var e = "<hr/>";
var array2=document.getElementsByClassName('tb2');
var e2 = "<hr/>";
for (var y=0; y<array.length; y++)
{
e += array[y].value ''+'' e2 += array2[y].value;
// e2 += "Mac " + y + " = " + array2[y].value;
}
document.getElementById("Result").innerHTML = e + 'm' + e2;
//document.getElementById("Result2").innerHTML = e;
}
//Counter to maintain number of textboxes and give them unique id for later reference
var intTextBox = 0;
var intTextBox2 = 0;
/**
* Function to add textbox element dynamically
* First we incrementing the counter and creating new div element with unique id
* Then adding new textbox element to this div and finally appending this div to main content.
*/
function addElement() {
intTextBox++;
intTextBox2++;
var objNewDiv = document.createElement('div');
objNewDiv.setAttribute('id', 'div_' + intTextBox);
objNewDiv.innerHTML = 'Textbox ' + intTextBox + ': <input type="text" id="tb_' + intTextBox + '" class="tb" name="tb_' + intTextBox + '"/>';
document.getElementById('content').appendChild(objNewDiv);
var objNewDiv = document.createElement('div');
objNewDiv.setAttribute('id', 'div_' + intTextBox);
objNewDiv.innerHTML = 'Textbox1 ' + intTextBox + ': <input type="text" id="tb2_' + intTextBox + '" class="tb2" name="tb2_' + intTextBox + '"/>';
document.getElementById('content').appendChild(objNewDiv);
}
<p>Demo of adding and removing textboxes dynamically using simple JavaScript</p>
<p>
Add
Remove
</p>
<div id="content"></div><div id="content2"></div>
<input type="button" id="button2" value="Display" onclick="display_array();"></input>
<div id="Result"></div>
So I have to use javascript and html to make a mad lib. I am asking the user to enter values and then hit the button and it is supposed to generate a story using the values they entered.
Here is my HTML:
<ul>
<li>Your Name: <input type="text" id="name"></li>
<li>Adjective: <input type="text" id="adjective"></li>
<li>State: <input type="text" id="state"></li>
<li>Animal: <input type="text" id="animal"></li>
<li>Month: <input type="text" id="month"></li>
<li>Adjective: <input type="text" id="adjective2"></li>
<li>Animal: <input type="text" id="animal2"></li>
<li>Object: <input type="text" id="object"></li>
</ul>
<button id="ready-button">Ready</button>
<div id="story"></div>
<script>
function madLib() {
var storyDiv = document.getElementById("story");
var adjective = document.getElementById("adjective").value;
var noun = document.getElementById("noun").value;
var state = document.getElementById("state").value;
var animal = document.getElementById("animal").value;
var month = document.getElementById("month").value;
var adjective2 = document.getElementById("adjective2").value;
var animal2 = document.getElementById("animal2").value;
var object = document.getElementById("object").value;
storyDiv.innerHTML ="One day, " + name + " was in the backwoods of " + state + " riding their pet " + animal + " it wasn't often that " + name + " got the chance to do this so they always made the most of their adventure. Usually, it was a fun experience until that one day in " + month + " they were minding their own business when all of the sudden the " + adjective2 + " " + animal2 + " jumped out from behind a small " + object + ". " + name + " could not beieve what they were seeing.";
}
var readyButton = document.getElementById('ready-button');
readyButton.addEventListener('click', madLib);
</script>
It seems that you got "noun" mixed up with "name" when grabbing the values for your story.
You have <input type="text" id="name"></li> and you use the name variable in your story a few times, but in the madLib function you have
var noun = document.getElementById("noun").value;
//document.getElementById("noun") will be undefined because there is no "noun element"
which should probably be
var name = document.getElementById("name").value;
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;
}