Beginner Javascript Advice - javascript

I'm new to Javascript and I can't understand why my code is not printing. I take in user input and it is supposed to print out to the textbox; can anyone help?
Forgive my ignorance, I'm a complete newbie with this.
Here's my code:
var $ = function(){
return document.getElementById(arguments[0]);
}
var protoStudent = {
college: "Athlone Institute of Technology",
course: "BSc (Hons) Software Design (Cloud computing)"
}
var createStudent = function(id, name, age){
var student = object.create(protoStudent);
student.id = id;
student.name = name;
student.age = age;
student.showDetails = function(){
return this.id + "\t" + this.name + "\t" + this.age + "\n";
}
return student;
}
var studentArray = [];
var addStudent = function(){
var id = $("studentID"). value;
var name = $("studentName").value;
var age = $("studentAge").value;
student = new createStudent(id, name, age);
studentArray[studentArray.length] = student;
showStudent();
}
var showStudent = function(){
var string = "ID" + "\t" + "Name" + "\t" + "Age" + "\n";
for (var i in studentArray){
string += studentArray[i].showDetails();
}
$("output").value = string;
}
window.onload = function(){
$("add").onclick = addStudent;
}
The html is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Student Register</title>
<link rel="stylesheet" type="text/css" href="StudentRegister.css" />
<script type="text/javascript" src="StudentRegister.js"></script>
<script type="text/javascript" src="shortcuts.js"></script>
</head>
<body>
<div id="content">
<h1>Student Register</h1>
<label for="studentID">Student ID:</label>
<input type="text"
id="studentID"
value="enter student ID here"
onfocus="this.value=''" /><br />
<label for="studentName">Student name:</label>
<input type="text"
id="studentName"
value="enter student name here"
onfocus="this.value=''" /><br />
<label for="studentAge">Student age:</label>
<input type="text"
id="studentAge"
value="enter student age here"
onfocus="this.value=''" /><br />
<br />
<label> </label>
<input type="button"
id="add"
value="Add" /><br />
<textarea id="output" rows="10" cols="60"></textarea>
</div>
</body>
</html>

When I tested your code the browser immediatly gave me this error:
Uncaught ReferenceError: object is not defined. test.php Line 15
Looking at line 15, you have:
var student = object.create(protoStudent);
However, as a case sensitive language you need:
var student = Object.create(protoStudent);
Javascript does not recognize your call to 'object' because only 'Object' is recognized as having the create method.
I tested, and this was working for me.
EDIT: On further reflection, you should check out jQuery so you don't have to declare $ for yourself.

Related

JavaScript input/output

JavaScript code is not reading my input in which is a name and should
have output saying Maurice is a very nice name. I think their is a
grammatical error that I am missing in my divOutput.
The program should take name input and output "Maurice is a very nice
name"
//text box
function sayHi() {
var txtName = document.getElementById("txtName");
var divOutput = document.getElementById("divOutput");
var name = txtName.value;
divOutput.innerHTML = "<em>" + name + "</em>";
divOutput.innerHTML = "is a very nice name.";
}
//end HI
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Inner.html</title>
<link rel="stylesheet" type="text/css" href="textBoxes.css" />
</head>
<body>
<h1>Inner HTML </h1>
<form action="">
<fieldset>
<label>Pleae type your name</label>
<input type="text" id="txtName" />
<button type="button" onclick="sayHi()">
Click Me
</button>
</fieldset>
</form>
<div id="divOutput">
Watch this space.
</div>
</body>
</html>
divOutput.innerHTML will replace whatever the divOutput have earlier, instead use +=.
function sayHi() {
var txtName = document.getElementById("txtName");
var divOutput = document.getElementById("divOutput");
var name = txtName.value;
divOutput.innerHTML += "<em>" + name + "</em>";
divOutput.innerHTML += " is a very nice name.";
}
<form action="">
<fieldset>
<label>Pleae type your name</label>
<input type="text" id="txtName" />
<button type="button" onclick="sayHi()">
Click Me
</button>
</fieldset>
</form>
<div id="divOutput">
Watch this space.
</div>
</body>
function sayHi()
{
var txtName = document.getElementById("txtName") ;
var divOutput = document.getElementById("divOutput") ;
var name = txtName.value;
divOutput.innerHTML = "<em>" + name + "</em> ";
divOutput.innerHTML += "is a very nice name.";
}
or
function sayHi()
{
var txtName = document.getElementById("txtName") ;
var divOutput = document.getElementById("divOutput") ;
var name = txtName.value;
divOutput.innerHTML = "<em>" + name + "</em> is a very nice name.";
}
Try this, you are overwriting html. Try this
function sayHi() {
var txtName = document.getElementById("txtName");
var divOutput = document.getElementById("divOutput");
var name = txtName.value;
divOutput.innerHTML = "<em>" + name + "</em> is a very nice name.";
// divOutput.innerHTML = "is a very nice name.";
}
Take a look at this code block where I modified your attempt just a tad.
In brief, you were almost there!
Note that in order to get the value of the element, you can use .value on what was retrieved from getElementById.
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<title>Inner.html</title>
<link rel="stylesheet" type="text/css" href="textBoxes.css" />
</head>
<body>
<h1>Inner HTML</h1>
<form>
<fieldset>
<label>Please type your name</label>
<input type="text" id="txtName" />
<button type="button" onclick="sayHi()">
Click Me
</button>
</fieldset>
</form>
<div id="divOutput">
Watch this space.
</div>
<script type="text/javascript">
//text box
function sayHi() {
var txtName = document.getElementById("txtName");
console.log(txtName.value); // <== use dot value to get the value.
var divOutput = document.getElementById("divOutput");
divOutput.innerHTML =
"<em>" + txtName.value + "</em> is a very nice name.";
}
//end HI
</script>
</body>
</html>

Pull value from HTML field and put into variable using get.element

How would i pull the user field info from the fields and store in a variable?
I need it to then output that information into a div, its for an employee records database kind of thing.
<!DOCTYPE html>
<html>
<head>
<title>52DA session 5</title>
<meta charset="utf-8" />
<link href="https://fonts.googleapis.com/css?family=Quicksand" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="../css/employee_styles.css"/>
</head>
<body>
<div id="container">
<header>
<h1 id="heading" class="blueTxt">Employee Records</h1>
</header>
<div class="left">
<form>
<fieldset>
<legend><h2>Employee Details Entry</h2></legend>
<p class=><label>Name: <input class="text" type="text" id="name" /></label></p>
<p><label>Age: <input class="text" type="text" id="age" /></label></p>
<p><label>Position: <input class="text" type="text" id="position" /></label></p>
<p><label>Details: <textarea type="text" id="details" maxlength="114" ></textarea></label></p>
<input class="button" type="button" id="addRecord" onclick="" value="Add Record"/>
</fieldset>
</form>
<div class="sort">
<h3>Sort</h3>
<button class="button" id="sortByName">By Name</button>
<button class="button" id="sortByAge">By Age</button>
<br/><button class="button" id="reset">Reset Details</button>
<br /><br />
</div>
</div>
<section>
<div id="employeeRecords">
</div>
</section>
</div>
<script src="../js/employee_script.js"></script>
</body>
</html>
heres my empty js
var employees = [];
//--------------------------------------------------------------------------------------------------------------
function Person(name, age, pos, dtls, img){
this.fullName = name;
this.employeeAge = age;
this.position = pos;
this.details = dtls;
this.avatarSrc = img;
this.createProfile = function(){
var profile = document.createElement("div");
profile.className = "profileStyle";
var avatar = document.createElement("img");
avatar.src = this.avatarSrc;
avatar.alt = this.fullName();
profile.appendChild(avatar);
var profileTxt = document.createElement("p");
profileTxt.innerHTML = "<b>" + this.fullName() +
"</b><br />" + this.age +
"</b><br />" + this.pos +
"</b><br />" + this.dtls;
profile.appendChild(profileTxt);
return profile;
}
employees.push(this);
please make it as simple as possible
cheers! any help will be appreciated!
Im fairly new to js and coding in general.
For getting values from HTML form fields from where you want to get value
var x = document.getElementById("myText").value;
and you can set it as where you want to set
document.getElementById("result").value = x;
I agree with #Rao and you can read this post that talk about how to get input field...
How do I get the value of text input field using JavaScript?
You can read from mozilla site
https://developer.mozilla.org/it/docs/Web/JavaScript/Guida
And w3schools...
https://www.w3schools.com/js/

JavaScript Error Finding the error on why my qty of items *cost of items won't give me a final answer

Can Someone help me? so my code allows me to send out an alert box when I run my system; first name, last name, street address, city, state, zip, something you want to buy and some type of amount. It runs but then it doesn't display the final amount of the (qty* cost of the item) at the end.
Am I missing something? how can I get it working?
Once I have the website I have no error, when I run it and it reaches the end I receive an error (Uncaught TypeError: Cannot set property 'value' of null) this line
if (document.getElementById("txtPurchase").value= "Gameboy"){
and <p><input type="button" value="Go!" name="btnSubmit" onclick="ordering()" ></p>
(Uncaught TypeError: Cannot set property 'value' of null
at ordering (line:35)
at HTMLInputElement.onclick (line:85)
ordering (line:35)
onclick (line:85)
<!DOCTYPE>
<html lang="en">
<head>
<meta charset="utf-8" />
<title> Confirmations on orders</title>
</head>
<body>
<script type="text/javascript">
function ordering() {
var firstName;
firstName = document.practiceForm.txtFirstName.value;
alert(firstName);
var lastName;
lastName = document.practiceForm.txtLastName.value;
alert(lastName);
var streetAddress;
streetAddress = document.practiceForm.txtStreetAddress.value;
alert(streetAddress);
var city;
city = document.practiceForm.txtCity.value;
alert(city);
var state;
state = document.practiceForm.txtState.value;
alert(state);
var zip;
zip = document.practiceForm.txtZip.value;
alert(zip);
if (document.getElementById("txtPurchase").value = "Gameboy") {
var gameboyPrice = 25;
var gameboyQuantity = document.getElementsById("quantity").value;
var gameboyTotal = gameboyPrice * gameboyQuantity;
alert("total: $" + gameboyTotal);
} else if (document.getElementById("txtPurchase").value = "DSI") {
var dsiPrice = 50;
var dsiQuantity = document.getElementsById("quantity").value;
var dsiTotal = dsiPrice * dsiQuantity;
alert("total: $" + dsiTotal);
} else if (document.getElementById("txtPurchase").value = "WII") {
var wiiPrice = 75;
var wiiQuantity = document.getElementsById("quantity").value;
var wiiTotal = wiiPrice * wiiQuantity;
alert("total: $" + wiiTotal);
}
}
</script>
<form name="practiceForm">
<p>First Name: <input type="text" name="txtFirstName"></p>
<p>Last Name: <input type="text" name="txtLastName"></p>
<p>Street Address: <input type="text" name="txtStreetAddress"></p>
<p>City: <input type="text" name="txtCity"></p>
<p>State: <input type="text" name="txtState"></p>
<p>Zip: <input type="text" name="txtZip"></p>
<p>What do you want to purchase today?:
<select id="txtPurchase">
<option value="Gameboy">Gameboy $25 each</option>
<option value="DSI">DSI $50 each</option>
<option value="WII">Wii $75 each</option>
</select>
</p>
<p>How much would you like to buy?: <input type="number" id="quantity"></p>
<p><input type="button" value="Go!" name="btnSubmit" onclick="ordering()"></p>
</form>
</body>
</html>
Use == instead of = in if conditions
And
In one place you use getElementsById("quantity")
Instead use getElementById("quantity") //No 's'
So your script tag should look like
<!DOCTYPE>
<html lang="en">
<head>
<meta charset="utf-8" />
<title> Confirmations on orders</title>
</head>
<body>
<script type="text/javascript">
function ordering() {
var firstName;
firstName = document.practiceForm.txtFirstName.value;
alert(firstName);
var lastName;
lastName = document.practiceForm.txtLastName.value;
alert(lastName);
var streetAddress;
streetAddress = document.practiceForm.txtStreetAddress.value;
alert(streetAddress);
var city;
city = document.practiceForm.txtCity.value;
alert(city);
var state;
state = document.practiceForm.txtState.value;
alert(state);
var zip;
zip = document.practiceForm.txtZip.value;
alert(zip);
if (document.getElementById("txtPurchase").value == "Gameboy") {
var gameboyPrice = 25;
var gameboyQuantity = document.getElementById("quantity").value;
var gameboyTotal = gameboyPrice * gameboyQuantity;
alert("total: $" + gameboyTotal);
} else if (document.getElementById("txtPurchase").value == "DSI") {
var dsiPrice = 50;
var dsiQuantity = document.getElementsById("quantity").value;
var dsiTotal = dsiPrice * dsiQuantity;
alert("total: $" + dsiTotal);
} else if (document.getElementById("txtPurchase").value == "WII") {
var wiiPrice = 75;
var wiiQuantity = document.getElementsById("quantity").value;
var wiiTotal = wiiPrice * wiiQuantity;
alert("total: $" + wiiTotal);
}
}
</script>
<form name="practiceForm">
<p>First Name: <input type="text" name="txtFirstName"></p>
<p>Last Name: <input type="text" name="txtLastName"></p>
<p>Street Address: <input type="text" name="txtStreetAddress"></p>
<p>City: <input type="text" name="txtCity"></p>
<p>State: <input type="text" name="txtState"></p>
<p>Zip: <input type="text" name="txtZip"></p>
<p>What do you want to purchase today?:
<select id="txtPurchase">
<option value="Gameboy">Gameboy $25 each</option>
<option value="DSI">DSI $50 each</option>
<option value="WII">Wii $75 each</option>
</select>
</p>
<p>How much would you like to buy?: <input type="number" id="quantity"></p>
<p><input type="button" value="Go!" name="btnSubmit" onclick="ordering()"></p>
</form>
</body>
</html>
var dsiQuantity=document.getElementsById("quantity").value;
you have a typo mistake here. Change it to
var dsiQuantity=document.getElementById("quantity").value;
Two things you need to change
1. in if condition - put == in place of =
2. for numeric value you need to parse them into proper number (i.e. int or float)
<!DOCTYPE>
<html lang="en">
<head>
<meta charset="utf-8" />
<title> Confirmations on orders</title>
</head>
<body>
<script type="text/javascript">
function ordering() {
var firstName;
firstName = document.practiceForm.txtFirstName.value;
console.log(firstName);
var lastName;
lastName = document.practiceForm.txtLastName.value;
console.log(lastName);
var streetAddress;
streetAddress = document.practiceForm.txtStreetAddress.value;
console.log(streetAddress);
var city;
city = document.practiceForm.txtCity.value;
console.log(city);
var state;
state = document.practiceForm.txtState.value;
console.log(state);
var zip;
zip = document.practiceForm.txtZip.value;
console.log(zip);
var purchase = document.getElementById("txtPurchase").value;
// parse value in Float type data.
var qty = parseFloat(document.getElementById("quantity").value);
// USE == for comparison
if (purchase == "Gameboy") {
var gameboyPrice = 25;
var gameboyTotal = gameboyPrice * qty;
alert("total: $" + gameboyTotal);
} else if (purchase == "DSI") {
var dsiPrice = 50;
var dsiTotal = dsiPrice * qty;
alert("total: $" + dsiTotal);
} else if (purchase == "WII") {
var wiiPrice = 75;
var wiiTotal = wiiPrice * qty;
alert("total: $" + wiiTotal);
}
}
</script>
<form name="practiceForm">
<p>First Name: <input type="text" name="txtFirstName"></p>
<p>Last Name: <input type="text" name="txtLastName"></p>
<p>Street Address: <input type="text" name="txtStreetAddress"></p>
<p>City: <input type="text" name="txtCity"></p>
<p>State: <input type="text" name="txtState"></p>
<p>Zip: <input type="text" name="txtZip"></p>
<p>What do you want to purchase today?:
<select id="txtPurchase">
<option value="Gameboy">Gameboy $25 each</option>
<option value="DSI">DSI $50 each</option>
<option value="WII">Wii $75 each</option>
</select>
</p>
<p>How much would you like to buy?: <input type="number" id="quantity"></p>
<p><input type="button" value="Go!" name="btnSubmit" onclick="ordering()">
</p>
</form>
</body>
</html>

My JS worked before and now it doesnt

I wanted to make a communication form and I literally copy pasted the code of a previously working one. The only changes I have made to the code are the text parts and CSS. All the name and ids are the same including the form. As I previously stated, literally a copy paste. I checked the console tab, no errors at all. At this point I'm confused. Any help is appreciated.
Code:
<DOCTYPE html>
<html>
<head>
<link REL="STYLESHEET" TYPE="TEXT/CSS" HREF="STYLES.css">
<title>ΣΕΛΙΔΑ ΕΠΙΚΟΙΝΩΝΙΑΣ</title>
</head>
<body>
<form name="CForm" id="CForm" method="post">
<h3>ΦΟΡΜΑ ΕΠΙΚΟΙΝΩΝΙΑΣ</h3>
<form name="myForm" id="form1" onsubmit="return validateForm()" method="post">
<label for="fname">ΟΝΟΜΑ ΚΑΙ ΕΠΩΝΥΜΟ </label>
<input type="text" id="fname" name="fname" placeholder="Ονομα&Επωνυμο" class="otherCFcss">
<label for="tel">ΤΗΛΕΦΩΝΟ</label>
<input type="text" id="tel" name="tel" placeholder="Τηλεφωνο.." class="otherCFcss">
<label for="lname">Email</label>
<input type="email" id="email" name="email" placeholder="something#something.com"><br>
<label for="subject">ΘΕΜΑ</label>
<textarea id="message" name="message" placeholder="Γραψε κατι.." style="height:200px" class="otherCFcss"></textarea>
<input type="submit" id="submitbutton" value="ΑΠΟΣΤΟΛΗ">
<input type="reset" id="resetbutton" value="ΑΚΥΡΩΣΗ">
</form>
</body>
</html>
<script>
var a = sessionStorage.getItem("a");
var b = sessionStorage.getItem("b");
var c = sessionStorage.getItem("c");
var d = sessionStorage.getItem("d");
document.getElementById("fname").value= a;
document.getElementById("tel").value= b;
document.getElementById("email").value= c;
document.getElementById("message").value= d;
function send() {
window.location.href = "mailto:dimtrispap1999#gmail.com?subject=Αυτόματο μήνυμα &body="+"Όνοματεπωνυμο: "+ a +"%0A"+"Τηλέφωνο:"+" "+ b +"%0A"+"Αίτημα,ερωτημα: "+d;
}
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
var y = document.forms["myForm"]["tel"].value;
var z = document.forms["myForm"]["email"].value;
var e = document.forms["myForm"]["message"].value;
if (x == "" || y == "" || z == "" || e == ""){
alert("Fill in the blanks");
} else {
var confirmwindow = window.open("", "_black", "width=560,height=190");
confirmwindow.document.writeln("<h3>Σιγουρα θελετε να στειλετε την παρακατω φορμα?</h3>");
confirmwindow.document.write("<b>Name*: </b>" + x + "<br>");
confirmwindow.document.writeln("<b>Τηλεφωνο*: </b>" + y + "<br>");
confirmwindow.document.writeln("<b>Email*: </b>" + z + "<br>");
confirmwindow.document.writeln("<b>Message*: </b><br>" + e + "<br><br>");
confirmwindow.document.write("<input type='submit' onclick='opener.send()' id='submitbutton' value='ΑΠΟΣΤΟΛΗ'>"+ " ");
confirmwindow.document.writeln("<input type='button' onclick='window.close();' id='resetbutton' value='cancel'>");
}
return false;
}
</script>
I also tried to add a variable outside the functions in both the previous and the current code.Something like that var x=document.forms["myForm"]["fname"].value;.In the previous code (the working one) there were no errors.
In the current one I get from the console this error:
Uncaught TypeError: Cannot read property 'fname' of undefined at
elidaepikoinwnias.html:35.
Line 35 is the line where I add the variable.Once I remove it the error is gone but still the JS code doesn't work.
Looks like you have a redundant and unclosed form - cForm
Remove this line
<form name="CForm" id="CForm" method="post">
You should not be nesting forms, check this

Javascript: Writing HTML dynamically via innerHTML

Im not sure why I cannot dynamically write to the paragraph element. I've even tried with just a string to no avail. What am I doing wrong here? Im guessing the default behavior is to POST because that's all that happens, even though I'm not telling it to do it.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
<!--
function submit() {
var fName = "";
var lName = "";
var eLevel = "";
fName = document.person.elements["fName"].value;
lName = document.person.elements["lName"].value;
eLevel = document.person.elements["eLevel"].value;
var result = fName + " " + lName + "<br>" + eLevel;
document.getElementById("result").innerHTML = result;
};
//-->
</script>
</head>
<body>
<form action="" id="person">
Please fill in all fields.<br /><br />
<fieldset><legend>Name:</legend>
First: <input type="text" id="fName" name="fName" /><br /><br />
Last:
<input type="text" id="lName" name="lName" />
</fieldset>
<br />
<fieldset>
<legend>Education:</legend>
Highest Level:
<input list="eLevels" name="eLevel" />
<datalist id="eLevels">
<option value="High School">
<option value="Associate Degree">
<option value="Bachelors Degree">
<option value="Graduate Degree">
</datalist>
</fieldset>
<br /><button value="click" onclick="submit()">click</button>
</form>
<p id="result"></p>
</body>
</html>
You need to preventDefault on the form submit, this way your code can execute.
function submit(event) {
event.preventDefault();
var fName = "";
var lName = "";
var eLevel = "";
fName = document.person.elements["fName"].value;
lName = document.person.elements["lName"].value;
eLevel = document.person.elements["eLevel"].value;
var result = fName + " " + lName + "<br>" + eLevel;
document.getElementById("result").innerHTML = result;
};
For the event parameter you will need to pass it in the onClick() event
<button value="click" onclick="submit(event)">click</button>

Categories