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>
Related
I'm a beginner in JavaScript and I'm trying to change the color of variable/element (name, age, and status) when it show the output in my JavaScript coding. For some reason the output not appear. Here is the code below:
<html>
<head>
<script>
function ageCalculator() {
var name = document.getElementById("name").value;
var birthdate = document.getElementById("dob").value;
var dob = new Date(birthdate);
var status;
if(birthdate==null || birthdate=='') {
document.getElementById("message").innerHTML = "<br><br>Choose a date properly!";
return false;
} else {
var month_diff = Date.now() - dob.getTime();
var age_date = new Date(month_diff);
var year = age_date.getUTCFullYear();
var age = Math.abs(year - 1970);
if (age<20)
status = "You are still young!";
else if (age>=20 && age<=25)
status = "Now start thinking to have your own family!";
else
status = "Be responsible and care about others!";
return document.getElementById("result").innerHTML =
" Hello " + name.css('color','red') + "<br><br> You are " + age.css('color','red') + " year-old" + "<br><br>" + status.css('color','red');
}
}
</script>
</head>
<body>
<center>
<b> Enter your name : <input type="text" id="name" name="name" ><br><br>
<b> Enter your birthday: <input type=date id = dob> </b>
<span id = "message" style="color:darkred"> </span> <br><br>
<button type="submit" onclick = "ageCalculator()"> Submit </button> <br>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4 id="result" align="center"></h4>
</center>
</body>
</html>
Here is the sample of the output:
enter image description here
You can add a CSS class in style tag and add a span tag around the text where you want to apply the style.
Add below style tag in your head element.
<style>
.txtColor {
color: red;
}
</style>
Now, in the innerHTML, add the span tag and apply the styles.
return document.getElementById("result").innerHTML =
" Hello <span class='txtColor'>" + name + "</span><br><br> You are <span class='txtColor'>" + age + "</span> year-old" + "<br><br><span class='txtColor'>" + status + "</span>";
Please mark this as an answer if it helps.
I want to output a function secret(); so it will look like this:
AAAA-BBB-<random string>
But it returns this error:
Uncaught TypeError: secret is not a function
Here is the code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Random End String</title>
<script type="text/javascript">
function writeName() {
var welcomeMsg = document.getElementById('welcome');
var name = document.getElementById('name');
var alamat = document.getElementById('alamat');
var secret = secret();
var formContent = document.getElementById('entername');
welcomeMsg.innerHTML = "Your Identifier is " + name.value + "-" + alamat.value + "-" + secret + "";
formContent.innerHTML = "";
}
</script>
<script>
function secret() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
</script>
</head>
<body>
<p id="welcome"></p>
<form id="entername">
Your Name:<input type="text" id="name" /><br/> LockerID:
<input type="text" id="alamat" /><br/>
<input type="hidden" id="secret">
<input type="button" value="Submit" onclick="writeName();" />
</form>
</body>
</html>
Don't name the var secret change it to something else in this example secret1 works fine'.
EDIT: You also need to return your "secret text".
Full working example:
function writeName() {
var welcomeMsg = document.getElementById('welcome');
var name = document.getElementById('name');
var alamat = document.getElementById('alamat');
var secret1 = secret();
var formContent = document.getElementById('entername');
welcomeMsg.innerHTML = "Your Identifier is " + name.value + "-" + alamat.value + "-" + secret1 + "";
formContent.innerHTML = "";
}
function secret() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text
}
function writeName1() {
var welcomeMsg = document.getElementById('welcome');
var name = document.getElementById('name');
var alamat = document.getElementById('alamat');
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
var formContent = document.getElementById('entername');
welcomeMsg.innerHTML = "Your Identifier is " + name.value + "-" + alamat.value + "-" + text + "";
formContent.innerHTML = "";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Random End String</title>
</head>
<body>
<p id="welcome"></p>
<form id="entername">
Your Name:<input type="text" id="name" /><br/> LockerID:
<input type="text" id="alamat" /><br/>
<input type="hidden" id="secret">
<input type="button" value="Submit" onclick="writeName();" />
</form>
</body>
</html>
Your Name:<input type="text" id="name1" /><br/> LockerID:
<input type="text" id="alama1t" /><br/>
<input type="hidden" id="secret1">
<input type="button" value="Submit" onclick="writeName1();" />
Your local variable secret is hiding your function secret. Simply rename the variable to something else to fix this issue
function writeName(){
var welcomeMsg = document.getElementById('welcome');
var name = document.getElementById('name');
var alamat = document.getElementById('alamat');
var secret = secret(); //right here this is your issue
var formContent = document.getElementById('entername');
welcomeMsg.innerHTML = "Your Identifier is "+name.value+"-"+alamat.value+"-"+secret+"";
formContent.innerHTML = "";
}
I have a problem with adding three input text fields after I put one button.
I'd like to have three new input fields after i push the button "Add author" - these inputs would be: 1. name 2. surname 3. initial. Everyone new input needs to have a different id in order to take the text from the inputs and show it in the new subpage which has to show up right after I push the button "Make the order".
<!DOCTYPE HTML>
<html lang='en'>
<head>
<meta charset='utf-8'>
<link rel='stylesheet' href='css/style.css'>
<script type="text/javascript">
window.onload = Load;
function Load()
{
document.getElementById('add_input').onclick = AddElement;
}
function AddElement()
{
var element = document.createElement('input');
var element2 = document.createElement('input');
var element3 = document.createElement('input');
element.setAttribute('type', 'text');
element.setAttribute('type', 'text');
element.setAttribute('type', 'text');
var number = 0;
var amount = document.forms['add_file'].elements.length;
for (var i = 0; i < ilosc; i++ )
{
if (document.forms['add_file'].elements[i].type == 'text')
{
number += 1;
}
}
element.setAttribute('name', 'file-'+(liczba+1));
element.setAttribute('nazwisko', 'file-'+(liczba+1));
element.style.display = "block";
element.style.margin= "2px";
document.forms['add_file'].appendChild(element);
}
</script>
<!--making order -->
<script>
function getText(){
var publisher = document.getElementById("publisher");
var year = document.getElementById("year");
var div = document.getElementById("readyorder")
div.innerHTML = "("+surname.value+" "+year.value+","+" "+"s."+" "+page.value+")";
}
</script>
</head>
<body>
<div class='container'>
<!-- header -->
<header>
<img src="images/header.jpg" alt=""/>
</header>
<input type="text" name="file-1" />
<input type="text" name="surname-1" />
<input type="submit" value="Add author" id="add_input" />
<form name="add_file" enctype="multipart/form-data" method="post">
</form>
Author's Surname<br>
<input type="text" id="surname"><br>
Page number<br>
<input type="text" id="page"><br>
Year<br>
<input type="text" id="year"><br/>
<input type="submit" value="Make the order" onclick="getText()" /> <br/><br/>
<div id="readyorder"></div><br/>
</body>
</html>
Store your id globaly and increase on each addition.
While Creating your node set their id value using setAttribute
element1.setAttribute('id', 'surname' + number);
Also Create a button while adding textbox's which let you know current order.
var button = document.createElement('input');
Add onclick attribute to call javascript function
button.setAttribute('onclick', 'getText(' + number + ')');
window.onload = Load;
var number = 0;
function Load()
{
document.getElementById('add_input').onclick = AddElement;
}
function AddElement()
{
var element1 = document.createElement('input');
var element2 = document.createElement('input');
var element3 = document.createElement('input');
var label1 = document.createElement('label');
var label2 = document.createElement('label');
var label3 = document.createElement('label');
var button = document.createElement('input');
label1.innerHTML = "</br>Author's Surname " + number + "</br>";
element1.setAttribute('type', 'text');
element1.setAttribute('id', 'surname' + number);
element1.setAttribute('placeholder', 'Surname...');
label1.appendChild(element1);
label2.innerHTML = '</br>Page number ' + number + '</br>';
element2.setAttribute('type', 'text');
element2.setAttribute('id', 'page' + number);
element2.setAttribute('placeholder', 'Page...');
label2.appendChild(element2);
label3.innerHTML = '</br>Year ' + number + '</br>';
element3.setAttribute('type', 'text');
element3.setAttribute('id', 'year' + number);
element3.setAttribute('placeholder', 'Year...');
label3.appendChild(element3);
button.setAttribute('onclick', 'getText(' + number + ')');
button.setAttribute('type', 'button');
button.setAttribute('value', 'Button ' + number);
document.forms['add_file'].appendChild(label1);
document.forms['add_file'].appendChild(label2);
document.forms['add_file'].appendChild(label3);
document.forms['add_file'].appendChild(button);
number++;
}
function getText(id)
{
var surname = document.getElementById("surname" + id);
var page = document.getElementById("page" + id);
var year = document.getElementById("year" + id);
var div = document.getElementById("readyorder")
div.innerHTML = "("+surname.value+" "+year.value+","+" "+"s."+" "+page.value+")";
}
<input type="text" name="file-1" />
<input type="text" name="surname-1" />
<input type="submit" value="Add author" id="add_input" />
<form name="add_file" enctype="multipart/form-data" method="post">
</form>
<hr>
<div id="readyorder"></div><br/>
This is my whole html page
<html>
<head>
<title> text conversion</title>
<script type="text/javascript">
function testResults(form)
{
var str = form.stringn.value;
str.split(" ");
document.write("testing1");
var length = str.length;
var newn = "";
for(var i = 0; i<length; i++)
{
if(str[i].charAt(str[i].length - 1) != ".")
{
str[i] = str[i] + ".";
}
str[i] = str[i] + " ";
str[i].charAt(0) = str[i].charAt(0).toUpperCase();
newn = newn + str[i];
}
document.write(newn);
document.write("testing");
}
</script>
</head>
<body>
<form name="stringform" action="" method="get">
Text: <input type="text" name="stringn"><br>
<input type="button" name="Convert" Value="convert" onClick="testResults(this.form)">
</form>
</body>
</html>
The html is being displayed correctly, but the button does not produce any action. I even tried document.write("testing") below the loop in the javascript, which had no effect, which makes me think the function is not being called at all. The idea of the function is to format the input string to capitalise the first letter of each word, and put a period after each word.
This is my first time trying to use javascript, so possibly I'm doing something wrong that should be obvious?
final solution:
<html>
<head>
<title> text conversion</title>
<script type="text/javascript">
function testResults(form)
{
var str = form.stringn.value;
var strn = str.split(" ");
var length = strn.length;
var newn = "";
for(var i = 0; i<length; i++)
{
if(strn[i].charAt(strn[i].length - 1) != ".")
{
strn[i] = strn[i] + ".";
}
strn[i] = strn[i].charAt(0).toUpperCase() + strn[i].slice(1);
strn[i] = strn[i] + " ";
newn = newn + strn[i];
}
document.write(newn);
}
</script>
</head>
<body>
<form name="stringform" action="" method="get">
Text: <input type="text" name="stringn"><br>
<input type="button" name="Convert" Value="convert" onClick="testResults(this.form)">
</form>
</body>
</html>
This should work. Also, echoing The comments before about using new as a variable.
<html>
<head>
<title> text conversion</title>
<script language="JavaScript">
function testResults(form)
{
var str = form.stringn.value;
var newString = "";
var strList = str.split(" ");
for(var i = 0; i < strList.length; i++){
newWord = strList[i].charAt(0).toUpperCase() + strList[i].slice(1) + ".";
newString += newWord + " ";
}
document.write(newString);
}
</script>
</head>
<body>
<form name="stringform" action="" method="get">
Text: <input type="text" name="stringn"><br>
<input type="button" name="Convert" Value="convert" onClick="testResults(this.form)">
</form>
</body>
</html>
Set <script type="text/javascript"> in your <head>!
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