I have a tiny problem with this college assignment. When the user inputs their data, an account id number is created. I've worked on that and it works like it should. But here's the problem: after the user clicks the submit button and the account id number is created, what they entered needs to be displayed below it. The assignment says I need to create a function called displayNewAccount and put in into one of the other functions. I put in inside the createEventListeners function. The text needs to be displayed in a custom ID (account) on the HTML page. The data entered into the first name input (fnameinput) should display after "First Name" (fname) and the last name input (lnameinput) should display after "Last Name" (lname) and so on. If the displayNewAccount function has to be moved inside another function then that is totally fine. I've looked online and found several examples, but I couldn't get them to work for me. What am I doing wrong? Thanks for the help.
HTML
<article>
<h2>New Account Information</h2>
<form>
<fieldset id="deliveryinfo">
<label>First Name</label><input type="text" id="fnameinput" name="fname">
<label>Last Name</label><input type="text" id="lnameinput" name="lname">
<label>Street Address</label><input type="text" id="addrinput" name="address">
<label>City</label><input type="text" id="cityinput" name="city">
<label>State</label><input type="text" id="stateinput" name="state">
<label>Zip</label><input type="text" id="zipinput" name="zip">
<label>Account ID</label><input type="text" id="accountidbox" name="accountid">
<input type="button" id="submitBtn" value="Create Account">
</fieldset>
<!-- New section -->
<fieldset>
<div id="account">
<!-- Data is displayed in here. -->
</div>
</fieldset>
</form>
</article>
JavaScript
var newAccountObject = {};
var newAccountSubmission;
function createID() {
var fname = document.getElementById("fnameinput");
var lname = document.getElementById("lnameinput");
var zip = document.getElementById("zipinput");
var account = document.getElementById("accountidbox");
var fields = document.getElementsByTagName("input");
var acctid;
var firstInit;
var lastInit;
if (fname !== "" || lname !== "" || zip !== "") {
firstInit = fname.value.charAt(0).toUpperCase();
lastInit = lname.value.charAt(0).toUpperCase();
acctid = firstInit + lastInit + zip.value;
account.value = acctid;
newAccountObject = {};
for(var i = 0; i < fields.length - 1; i++) {
newAccountObject[fields[i].name] = fields[1].value;
}
}
}
function createString() {
newAccountSubmission = JSON.stringify(newAccountObject);
}
function createEventListeners() {
var fname = document.getElementById("fnameinput");
var lname = document.getElementById("lnameinput");
var zip = document.getElementById("zipinput");
if (fname.addEventListener) {
fname.addEventListener("change", createID, false);
lname.addEventListener("change", createID, false);
zip.addEventListener("change", createID, false);
}
else if (fname.attachEvent) {
fname.attachEvent("onchange", createID);
lname.attachEvent("onchange", createID);
zip.attachEvent("onchange", createID);
}
if (button.addEventListener) {
button.addEventListener("click", createString, false);
}
else if (button.attachEvent) {
button.attachEvent("onclick", createString);
}
// Displays an account summary section when the "Create Account" button is clicked.
function displayNewAccount() {
document.getElementById("account").innerHTML = "First Name: " + fname + "<br>" + "Last Name: " + lname + "<br>" + "Address: " + addrinput + "<br>" + "City: " + cityinput + "<br>" + "State: " + stateinput + "<br>" + "Zip: " + zipinput + "<br>" + "Account ID: " + accountidbox;
}
if (window.addEventListener) {
window.addEventListener("click", displayNewAccount, false);
}
else if (window.attachEvent) {
window.attachEvent("onclick", displayNewAccount);
}
}
if (window.addEventListener) {
window.addEventListener("load", createEventListeners, false);
}
else if (window.attachEvent) {
window.attachEvent("onload", createEventListeners);
}
Related
I am using the following code to generate a user-defined number of text inputs via a loop.
The generated inputs vanish after being generated in the loop - I am not sure why? I suspect I am missing something very simple?
The next step for the program will be to take the user input from the generated text inputs and put them into an array of arrays if that's in any way relevant?
function Player_Entry(){
Loop_End = document.getElementById('Select_Number_Of_Players').value;
for (Loop_Count = 0; Loop_Count < Loop_End; Loop_Count++) {
Variable_Name = "Player_Name_" + Loop_Count + 1
Variable_Number = "Player_Number_" + Loop_Count + 1
console.log("Created, Variable Number: " + Variable_Name);
console.log("Created, Variable Name: " + Variable_Number);
var Variable_Name = document.createElement("input");
Variable_Name.type = "text";
Variable_Name.value = "";
document.getElementById('Generated_Form').appendChild(Variable_Name);
}
}
<form onsubmit="Player_Entry()">
<label for="Number_Of_Players">Number of players</label>
<input type="number" id="Select_Number_Of_Players" value="1" name="Number_Of_Players" min=1 max =12><input type ="submit">
</form>
<br>Enter Player Names<br>
<form id="Generated_Form"></form>
Any help, particularly pointing out obvious rookie errors, gratefully recieved.
It's because the input's type is set to submit, which causes the form to be submitted when it is clicked.
You can stop the form from submitting by adding return false in the onsubmit handler:
function Player_Entry() {
Loop_End = document.getElementById('Select_Number_Of_Players').value;
for (Loop_Count = 0; Loop_Count < Loop_End; Loop_Count++) {
Variable_Name = "Player_Name_" + Loop_Count + 1
Variable_Number = "Player_Number_" + Loop_Count + 1
console.log("Created, Variable Number: " + Variable_Name);
console.log("Created, Variable Name: " + Variable_Number);
var Variable_Name = document.createElement("input");
Variable_Name.type = "text";
Variable_Name.value = "";
document.getElementById('Generated_Form').appendChild(Variable_Name);
}
}
<form onsubmit="Player_Entry(); return false">
<label for="Number_Of_Players">Number of players</label>
<input type="number" id="Select_Number_Of_Players" value="1" name="Number_Of_Players" min=1 max=12/> <input type="submit" />
</form>
<br>Enter Player Names<br>
<form id="Generated_Form"></form>
either change the submit button to a button or preventDefault() to stop the submission of the form
function Player_Entry(){
event.preventDefault();
Loop_End = document.getElementById('Select_Number_Of_Players').value;
for (Loop_Count = 0; Loop_Count < Loop_End; Loop_Count++) {
Variable_Name = "Player_Name_" + Loop_Count + 1
Variable_Number = "Player_Number_" + Loop_Count + 1
console.log("Created, Variable Number: " + Variable_Name);
console.log("Created, Variable Name: " + Variable_Number);
var Variable_Name = document.createElement("input");
Variable_Name.type = "text";
Variable_Name.value = "";
document.getElementById('Generated_Form').appendChild(Variable_Name);
}
}
<form onsubmit="Player_Entry()">
<label for="Number_Of_Players">Number of players</label>
<input type="number" id="Select_Number_Of_Players" value="1" name="Number_Of_Players" min=1 max =12><input type ="submit">
</form>
<br>Enter Player Names<br>
<form id="Generated_Form"></form>
I can't figure out why this code won't display the user entered information. I need to have user enter information from the html form, add this info to the arrays, and then display the info (actually, need to do more than this, but can't get past this point). I need the entered information to display on the page. Thanks
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Homework 10</title>
<script type="text/javascript">
//Variables for arrays
var fName = [];
var lName = [];
var tScore = [];
//Variables from user input
var fNameInput = document.getElementById("firstName");
var lNameInput = document.getElementById("lastName");
var tScoreInput = document.getElementById("testScore");
//Variable for display
var display = document.getElementById("display");
//Function to add user info to arrays
function insert() {
fName.push(fNameInput.value);
lName.push(lNameInput.value);
tScore.push(tScoreInput.value);
clearAndShow();
}
//Function to display info entered from array
function clearAndShow() {
fNameInput.value = "";
lNameInput.value = "";
tScoreInput.value = "";
display.innerHTML = "";
display.innerHTML += "First Name: " + fName.join(", ") + "<br/>";
display.innerHTML += "LastName: " + lName.join(", ") + "<br/>";
display.innerHTML += "Test Score: " + tScore.join(", ") + "<br/>";
}
</script>
</head>
<body bgcolor="Cornsilk">
<h2>Average Student Scores</h2>
<form>
<fieldset>
<legend><strong>Enter First, Last Name and Test Score:</strong></legend><br />
<input type="text" id="firstName" placeholder="First name"/><p />
<input type="text" id="lastName" placeholder="Last name"/><p />
<input type="number" id="testScore" placeholder="Test Score"/><p />
<input type="button" value="Save/Show Average" onclick="insert()"/><p />
</fieldset><p />
</form>
<div id="display"></div>
</body>
</html>
I tried to run the code. I got an error like
test.html:23 Uncaught ReferenceError: fName is not defined
You can solve this by moving the variable declaration inside the function.
//Variables for arrays
var fName = [];
var lName = [];
var tScore = [];
//Function to add user info to arrays
function insert() {
var fNameInput = document.getElementById("firstName");
var lNameInput = document.getElementById("lastName");
var tScoreInput = document.getElementById("testScore");
fName.push(fNameInput.value);
lName.push(lNameInput.value);
tScore.push(tScoreInput.value);
clearAndShow();
}
//Function to display info entered from array
function clearAndShow() {
var display = document.getElementById("display");
var fNameInput = document.getElementById("firstName");
var lNameInput = document.getElementById("lastName");
var tScoreInput = document.getElementById("testScore");
fNameInput.value = "";
lNameInput.value = "";
tScoreInput.value = "";
display.innerHTML = "";
display.innerHTML += "First Name: " + fName.join(", ") + "<br/>";
display.innerHTML += "LastName: " + lName.join(", ") + "<br/>";
display.innerHTML += "Test Score: " + tScore.join(", ") + "<br/>";
}
The reason for this is the element is no there when the initial declaration is happening.
Move the script below the body
The main issue is that the Javascript is loaded before the HTML. As a result, when the Javascript attempts to find the element with the element "firstName", it fails to find it because it hasn't been loaded yet.
To fix this, you should move the script tag below the body tag so that the HTML is loaded before it is accessed by the Javascript.
As an added bonus, it improves page load time as the browser doesn't have to wait for the JavaScript to load before rendering the HTML
Example Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Homework 10</title>
</head>
<body bgcolor="Cornsilk">
<h2>Average Student Scores</h2>
<form>
<fieldset>
<legend><strong>Enter First, Last Name and Test Score:</strong></legend><br />
<input type="text" id="firstName" placeholder="First name"/><p />
<input type="text" id="lastName" placeholder="Last name"/><p />
<input type="number" id="testScore" placeholder="Test Score"/><p />
<input type="button" value="Save/Show Average" onclick="insert()"/><p />
</fieldset><p />
</form>
<div id="display"></div>
</body>
<script type="text/javascript">
//Variables for arrays
var fName = [];
var lName = [];
var tScore = [];
//Variables from user input
var fNameInput = document.getElementById("firstName");
var lNameInput = document.getElementById("lastName");
var tScoreInput = document.getElementById("testScore");
//Variable for display
var display = document.getElementById("display");
//Function to add user info to arrays
function insert() {
fName.push(fNameInput.value);
lName.push(lNameInput.value);
tScore.push(tScoreInput.value);
clearAndShow();
}
//Function to display info entered from array
function clearAndShow() {
fNameInput.value = "";
lNameInput.value = "";
tScoreInput.value = "";
display.innerHTML = "";
display.innerHTML += "First Name: " + fName.join(", ") + "<br/>";
display.innerHTML += "Last Name: " + lName.join(", ") + "<br/>";
display.innerHTML += "Test Score: " + tScore.join(", ") + "<br/>";
}
</script>
</html>
I have a program where the user enters two inputs, and then when the display button is pressed, the multiplication table within the parameters of those two numbers is displayed. However, when I press the button, nothing is displayed.
<span style = "font-size:15px">First Number: </span><input type = "text" id = "first_num" style = "font-size:18px"> <br /><br />
<span style = "font-size:15px">Second Number: </span><input type = "text" id = "second_num" style = "font-size:18px"> <br /><br />
<button type = "button" onclick = "display()">Display</button> <br /><br />
<script type = "text/javascript">
var f_num = document.getElementById("first_num").value;
var s_num = document.getElementById("second_num").value;
function display() {
for (i=1;i<f_num + 1;i++) {
for (j=1;j<s_num + 1;j++) {
if (j == 10) {
document.write(i+"*" +j +"=" +(i*j) + "<br /><br />")
} else {
document.write(i+"*" +j +"=" +(i*j) + " | ")
}
}
}
}
</script>
you should set your variable within the function.in your current code they are being set when the first time script is getting executed and at that time they have blank value.
Correct code will be.
function display() {
var f_num = parseInt(document.getElementById("first_num").value);
var s_num = parseInt(document.getElementById("second_num").value);
for (i=1;i<f_num + 1;i++) {
for (j=1;j<s_num + 1;j++) {
if (j == 10) {
document.write(i+"*" +j +"=" +(i*j) + "<br /><br />");
} else {
document.write(i+"*" +j +"=" +(i*j) + " | ");
}
}
}
}
You can check things on the below plunker.
https://plnkr.co/edit/kgWaEG1ZvgST0RclvV2l?p=preview
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
UPDATE
Ok, after trying ".value" for god knows x amount of time again, it some how worked..... Problem solved. Thanks a lot for those who has responded.
UPDATE
How can I obtain the text(strings) from my form on my HTML page with Javascript?
I just want to take whatever was inputted into the text box and write into my XML file.
For example, if I type "HELLO" into the text box, I want "HELLO" written in the XML file.
I have tried both ".value" and ".text", they don't work. Also tried ".textcontent", no good too. I'm thinking that I need to use a different code.
Here's an image of what I'm trying to do:
http://img94.imageshack.us/img94/5677/sdfsdfsdfs.jpg
Here are the files if you want to mess with them personally:
http://www.mediafire.com/?e29t6ipatsqun70
Here's my HTML file:
<html>
<!--onSubmit="SaveXML(person);"-->
<head>
<title>Registration</title>
<link rel="stylesheet" type="text/css" href="CSS_LABs.css" />
</head>
<body>
<script type="text/javaScript" src="LoginJS.js"> </script>
<script type="text/javaScript" src="writeXML.js"> </script>
<div class="form">
<form id="Registration" name="reg" action="" method="get" onSubmit="initialize_array()">
Username:<input type="text" name="Usrname" id="Usrname" maxlength="10"/> <br/>
Password:<input type="password" name="Pswd" id="Pswd" maxlength="20"/> <br/>
<hr>
PersonID:<input type="text" name="PersonID" id="PersonID"/> <br>
<hr>
First Name:<input type="text" name="FirstName" id="FirstName"/> <br>
Last Name:<input type="text" name="LastName" id="LastName"/>
<hr>
DOB:<input type="text" name="DOB" id="DOB"/> <br>
<hr>
Gender:<input type="text" name="Gender" id="Gender"/> <br>
<hr>
Title:<input type="text" name="Title" id="Title"/> <br>
<hr>
<!--Secret Question:<br>
<select name="secret?">
</select> <br>
Answer:<input type="text" name="answer" /> <br> <br>-->
<input type="submit" value="submit" />
</form>
</div>
</body>
</html>
Here's my Javascript file:
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
var fso = new ActiveXObject("Scripting.FileSystemObject");
var FILENAME = 'G:\\CST2309 - Web Programming 1\\Copy of Take Home Exam - Copy\\PersonXML2.xml';
function SaveXML(UserData)
{
var usrn = document.getElementById("Username").text;
var pswd = document.getElementById("Pswd").text;
var pid = document.getElementById("PersonID").text;
var fname = document.getElementById("FirstName").text; //This is where I'm having trouble with
var lname = document.getElementById("LastName").text;
var gender = document.getElementById("Gender").text;
var dob = document.getElementById("DOB").text;
var title = document.getElementById("Title").text;
var file = fso.CreateTextFile(FILENAME, true);
file.WriteLine('<?xml version="1.0" encoding="utf-8"?>\n');
file.WriteLine('<PersonInfo>\n');
for (countr = 0; countr < UserData.length; countr++) {
file.Write(' <Person ');
file.Write('Usrname="' + UserData[countr][0] + '" ');
file.Write('Pswd="' + UserData[countr][1] + '" ');
file.Write('PersonID="' + UserData[countr][2] + '" ');
file.Write('FirstName="' + UserData[countr][3] + '" ');
file.Write('LastName="' + UserData[countr][4] + '" ');
file.Write('Gender="' + UserData[countr][5] + '" ');
file.Write('DOB="' + UserData[countr][6] + '" ');
file.Write('Title="' + UserData[countr][7] + '"');
file.WriteLine('></Person>\n');
} // end for countr
file.Write(' <Person ');
file.Write('Usrname="' + usrn + '" ');
file.Write('Pswd="' + pswd + '" ');
file.Write('PersonID="' + pid + '" ');
file.Write('FirstName="' + fname + '" ');
file.Write('LastName="' + lname + '" ');
file.Write('Gender="' + gender + '" ');
file.Write('DOB="' + dob + '" ');
file.Write('Title="' + title + '" ');
file.WriteLine('></Person>\n');
file.WriteLine('</PersonInfo>\n');
file.Close();
} // end SaveXML function --------------------
function LoadXML(xmlFile)
{
xmlDoc.load(xmlFile);
return xmlDoc.documentElement;
} //end function LoadXML()
function initialize_array()
{
var person = new Array();
var noFile = true;
var xmlObj;
if (fso.FileExists(FILENAME))
{
xmlObj = LoadXML(FILENAME);
noFile = false;
} // if
else
{
xmlObj = LoadXML("PersonXML.xml");
//alert("local" + xmlObj);
} // end if
var usrCount = 0;
while (usrCount < xmlObj.childNodes.length)
{
var tmpUsrs = new Array(xmlObj.childNodes(usrCount).getAttribute("Usrname"),
xmlObj.childNodes(usrCount).getAttribute("Pswd"),
xmlObj.childNodes(usrCount).getAttribute("PersonID"),
xmlObj.childNodes(usrCount).getAttribute("FirstName"),
xmlObj.childNodes(usrCount).getAttribute("LastName"),
xmlObj.childNodes(usrCount).getAttribute("Gender"),
xmlObj.childNodes(usrCount).getAttribute("DOB"),
xmlObj.childNodes(usrCount).getAttribute("Title"));
person.push(tmpUsrs);
usrCount++;
} //end while
if (noFile == false)
fso.DeleteFile(FILENAME);
SaveXML(person);
} // end function initialize_array()
You can use document.getElementById("UsrName").value to get tha value of a field in your form. Due to you use id for every field, so there is no problem using this code.
Something around: http://www.tek-tips.com/viewthread.cfm?qid=1143011&page=1
Here is an example of it working. I changed some functionality around just to show that the function was seeing the values correctly:
http://jsfiddle.net/73gbH/1
But like everyone said change .text to .value