I have an HTML/Javascript document that outputs the grade of a student based on the inputs of my form. The mechanics of the grade calculation should be working, but the final output does not. The main thing I'm honing in on is the document.getElementById("span1").innerHTML and span2's same code. I want these to change the inner HTML to the values I calculated with my code, but they remain at X and yy even when I attempt to change them.
I think the error should be in my calculateGrade function or in my HTML. I did not include the rest of the code to simplify my post, so the error lay outside of where I think it does. I need the output paragraph to have the correct values, but they are not being changed.
Even if I change the new innerHTML values to concrete values such as P and 88, the code displays X and yy instead. I set a default "A" and "91" to test it and receive the same problem. I think there may be an issue with my form gets as changing the value of the name in the form also doesn't change my final output.
This is my first Javascript/HTML project, and I'm very desperate to get it working. I'm already one day late, and in a couple hours, it will be two. I deeply appreciate any hep I can get. Thanks guys. Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Joe Peterson's Assignment 7</title>
<script>
function calculateGrade(){
document.getElementById("form1").style.display = "none";
document.getElementById("p1").style.display = "block";
alert(document.getElementById("FirstName").value);
var fname = document.getElementById("LastName").value;
var lname = document.getElementById("FirstName").value;
var valMidterm = document.getElementById("MidtermScore").value;
var valFinal = document.getElementById("FinalScore").value;
var lMidterm = document.getElementById("MidtermLetter").value;
var lFinal = document.getElementById("FinalLetter").value;
var homeworkArray = document.getElementById("HomeworkScores").value.split(',');
var classworkArray = document.getElementById("ActivityScores").value.split(',');
var grade = "A";
var score = 91;
document.getElementById("span1").innerHTML = (grade);
document.getElementById("span2").innerHTML = (score);
document.getElementById("fname").innerHTML = (fname);
document.getElementById("lname").innerHTML = (lname);
return false;
}
</script>
</head>
<body>
<p><h1>Joe Peterson's Assignment 7</h1></p>
<form name="input" id="form1" onsubmit="calculateGrade()" style="display:form">
First name: <input type="text" name="FirstName" id="FirstName" value="Joe"><br>
Last name: <input type="text" name="LastName" id="LastName" value="Peterson"><br>
Homework Scores (separate with commas): <input type="text" name="HomeworkScores" id="HomeworkScores" value="90, 80, 98"><br>
Activity Scores (separate with commas): <input type="text" name="ActivityScores" id="ActivityScores" value="71, 65, 96"><br>
Midterm Exam Percentage: <input type="text" name="MidtermScore" id="MidtermScore" value="91"><br>
Midterm Exam Letter Grade: <input type="text" name="MidtermLetter" id="MidtermLetter" value="A"><br>
Final Exam Percentage: <input type="text" name="FinalScore" id="FinalScore" value="75"><br>
Final Exam Letter Grade: <input type="text" name="FinalLetter" id="FinalLetter" value="C"><br>
<input type="submit" value="Submit">
</form>
<p id="p1" style="display:none">
Final course grade for
<span id="fname">Joe</span> <span id="lname">Peterson</span>
is: <span id="span1">X</span> (<span id="span2">yy</span>%)
</p>
</body>
</html>
Just move the alert call to the end of the function, and it will work finely:
function calculateGrade(){
document.getElementById("form1").style.display = "none";
document.getElementById("p1").style.display = "block";
var fname = document.getElementById("LastName").value;
var lname = document.getElementById("FirstName").value;
var valMidterm = document.getElementById("MidtermScore").value;
var valFinal = document.getElementById("FinalScore").value;
var lMidterm = document.getElementById("MidtermLetter").value;
var lFinal = document.getElementById("FinalLetter").value;
var homeworkArray = document.getElementById("HomeworkScores").value.split(',');
var classworkArray = document.getElementById("ActivityScores").value.split(',');
var grade = "A";
var score = 91;
document.getElementById("span1").innerHTML = grade;
document.getElementById("span2").innerHTML = score;
document.getElementById("fname").innerHTML = fname;
document.getElementById("lname").innerHTML = lname;
alert(document.getElementById("FirstName").value);
return false;
}
And set your form action to return calculateGrade() as Patrick Evans mentioned in his comment.
here's a demo
And as
Like this should be ok...I only change the input type to "button"
<!DOCTYPE html>
<html>
<head>
<title>Joe Peterson's Assignment 7</title>
<script>
function calculateGrade(){
document.getElementById("form1").style.display = "none";
alert(document.getElementById("FirstName").value);
var fname = document.getElementById("LastName").value;
var lname = document.getElementById("FirstName").value;
var valMidterm = document.getElementById("MidtermScore").value;
var valFinal = document.getElementById("FinalScore").value;
var lMidterm = document.getElementById("MidtermLetter").value;
var lFinal = document.getElementById("FinalLetter").value;
var homeworkArray = document.getElementById("HomeworkScores").value.split(',');
var classworkArray = document.getElementById("ActivityScores").value.split(',');
var grade = "A";
var score = 91;
document.getElementById("span1").innerHTML = (grade);
document.getElementById("span2").innerHTML = (score);
document.getElementById("fname").innerHTML = (fname);
document.getElementById("lname").innerHTML = (lname);
document.getElementById("p1").style.display = "block";
return false;
}
</script>
</head>
<body>
<p><h1>Joe Peterson's Assignment 7</h1></p>
<form name="input" id="form1"style="display:form">
First name: <input type="text" name="FirstName" id="FirstName" value="Joe"><br>
Last name: <input type="text" name="LastName" id="LastName" value="Peterson"><br>
Homework Scores (separate with commas): <input type="text" name="HomeworkScores" id="HomeworkScores" value="90, 80, 98"><br>
Activity Scores (separate with commas): <input type="text" name="ActivityScores" id="ActivityScores" value="71, 65, 96"><br>
Midterm Exam Percentage: <input type="text" name="MidtermScore" id="MidtermScore" value="91"><br>
Midterm Exam Letter Grade: <input type="text" name="MidtermLetter" id="MidtermLetter" value="A"><br>
Final Exam Percentage: <input type="text" name="FinalScore" id="FinalScore" value="75"><br>
Final Exam Letter Grade: <input type="text" name="FinalLetter" id="FinalLetter" value="C"><br>
<input type="button" value="Submit" onclick="calculateGrade()">
</form>
<p id="p1" style="display:none">
Final course grade for
<span id="fname">Joe</span> <span id="lname">Peterson</span>
is: <span id="span1">X</span> (<span id="span2">yy</span>%)
</p>
</body>
</html>
Related
I am creating a simple equation solver that involves division. I have two text boxes, One for "Mass" and one for "Element". I want to create a variable "H" and set it equal to 1, that way when the user types in "2" in the mass box and "H" in the element box, the output will say "1".
Here is my HTML
<div id="GramsToMolesContainer"><div id="GramMolesText">
<font size=3>Grams To Moles</font></div>
<form>
Grams : <input type="text" id="GramsChoice" /><br>
Element : <input type="text" id="ElementChoice" /><br>
<input type="button" onClick="GramstoMoles()" Value="Convert" />
</form>
<p>Molar Mass : <br>
<span id = "resultMolarMass"></span>
</p>
</div>
Here is my Javascript:
function GramstoMoles()
{
var H = 1;
GramsState = document.getElementById("GramsChoice").value;
ElementState =
document.getElementById("ElementChoice").value;
document.getElementById("resultMolarMass").innerHTML
= GramsState / ElementState;
}
you will need to create a dictionary.
this is how your function should look. every time that you want to add an element - create a new key-value pair.
function GramstoMoles()
{
var elements = {h:1, he:2};
GramsState = document.getElementById("GramsChoice").value;
ElementState =
document.getElementById("ElementChoice").value;
document.getElementById("resultMolarMass").innerHTML
= parseInt(GramsState) / elements[ElementState];
}
Check this working snippet of your code!
If you wan to set H as an inital value of some box, do
var ElementState = document.getElementById("ElementChoice").value = H; before you call the function.
function GramstoMoles (){
var H = 1;
var GramsState = document.getElementById("GramsChoice").value;
var ElementState = document.getElementById("ElementChoice").value;
document.getElementById("resultMolarMass").innerHTML = GramsState / ElementState;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="GramsToMolesContainer"><div id="GramMolesText">
<font size=3>Grams To Moles</font></div>
<form>
Grams : <input type="text" id="GramsChoice" /><br>
Element : <input type="text" id="ElementChoice" /><br>
<input type="button" onClick="GramstoMoles()" Value="Convert" />
</form>
<p>Molar Mass : <br>
<span id = "resultMolarMass"></span>
</p>
</div>
When you get the var element and var grams ,
var elements = ['H','He','Li','Be',...];
var atomicmasses = [1,4,6,9,.....];
var molarmass = molarmasses[elements.indexOf(element)];
var mole = grams/molarmass;
I create a multiphase form (wizards from) and I want to show in the last step all Information in input text (you can modify it) before validate
I try a lot but without any result, how can I do it ?
My code
var fname, lname, age;
function _(x) {
return document.getElementById(x);
}
function processPhase1(){
fname = _("firstname").value;
lname = _("lastname").value;
if(fname.length > 2 && lname.length > 2){
_("phase1").style.display = "none";
_("phase2").style.display = "block";
}
else {alert("Please Enter All Information");}
}
function processPhase2(){
age = _("age").value;
if(age.length >= 1){
_("phase2").style.display = "none";
_("show_info").style.display = "block";
}
else {alert("Please Enter All Information");}
}
<body>
<div id="phase1">
First Name : <input id="firstname" name="firstname"><br>
Last Name : <input id="lastname" name="lastname"><br>
<button onclick="processPhase1()">Next</button>
</div>
<div id="phase2">
Age : <input id="age" name="age"><br>
<button onclick="processPhase2()">Next</button>
</div>
<div id="show_info">
First Name : <input id="firstname" name="firstname" value = ""><br>
Last Name : <input id="lastname" name="lastname" value = ""><br>
Age : <input id="age" name="age" value = ""><br>
<button onclick="submit()">submit</button>
</div>
I try this but it's just for showing Information, but you can't modify it, I need to show it in input text
function processPhase2(){
age = _("age").value;
if(age.length >= 1){
_("phase2").style.display = "none";
_("show_info").style.display = "block";
_("display_fname").innerHTML = fname;
_("display_lname").innerHTML = lname;
_("display_age").innerHTML = age;
}
else {alert("Please Enter All Information");}
}
<div id="show_info">
First Name : <span id="display_fname"></span><br>
Last Name : <span id="display_lname"></span><br>
Age : <span id="display_age"></span><br>
<button onclick="submit()">submit</button>
</div>
I would have done this completely different, but this is how you would do it based on what you've already written. When you click the next button in each function, you want to grab that value of (fname, lname, or age) and set the value of that to the value of the last set of inputs. I've altered your code a bit and made you a JS BIN http://jsbin.com/sopikuzuri/edit?html,output
In simple terms
Each time you call a new phase function (processPhase1), you want to grab the values of what the user just entered.
Then, you want to set those values to the proper <input />
So, the simplest example I can give is this:
Below, the user will enter some data into the field. When they click the submit phase 1 button we will grab the value of what they just entered and set that value to the last input (for them to see/edit)
<input type="text" id="firstName"/>
<button id="submit">Submit Phase 1</button>
<input type="text" id="displayInput"/>
<script>
$("#submit").click(function() {
// getting the value of what the user typed in
var fname = $("#firstName").value;
// setting the value of the final box to the var above
$("#displayInput").val(fname);
});
</script>
Obviously, a beginner's question:
How do I get array data to display in an html element using html and javascript?
I'd like to display the user saved array data in a paragraph tag, list tag, or table tag, etc.
[http://www.mysamplecode.com/2012/04/html5-local-storage-session-tutorial.html]
Above is a link to the kindly provided example of localStorage except how to display the array on the html page rather than in the console.log.
Below is the code snip that demonstrates what I'm trying to do.
function saveArrayData() {
console.log("Saving array data to local storage.");
var myArrayObject = [];
var personObject1 = new Object();
personObject1.name = "Array1";
personObject1.age = 23;
myArrayObject.push(personObject1);
var personObject2 = new Object();
personObject2.name = "Array2";
personObject2.age = 24;
myArrayObject.push(personObject2);
var personObject3 = new Object();
personObject3.name = "Array3";
personObject3.age = 25;
myArrayObject.push(personObject3);
localStorage.setItem("persons", JSON.stringify(myArrayObject));
}
function restoreArrayData() {
console.log("Restoring array data from local storage.");
var myArrayObject = JSON.parse(localStorage.getItem("persons"));
for (var i = 0; i < myArrayObject.length; i++) {
var personObject = myArrayObject[i];
console.log("Name: " + personObject.name, "Age: " + personObject.age);
}
}
<label for="name">Name:</label>
<input type="text" data-clear-btn="true" name="name" id="name" value="">
<label for="age">Age:</label>
<input type="text" data-clear-btn="true" name="age" id="age" value="">
<br>
<br>
<input type="button" id="sArray" value="Save Array data" onclick="Javascript:saveArrayData()">
<input type="button" id="rArray" value="Restore Array data" onclick="Javascript:restoreArrayData()">
<p id="displayArrayDataHere"></p>
You should update your code like below:
function restoreArrayData() {
var myArrayObject = JSON.parse(localStorage.getItem("persons"));
$("#displayArrayDataHere").append("<table>");
myArrayObject.forEach(function(personObject) {
$("#displayArrayDataHere").append("<tr><td>"+personObject.name+"</td><td>"+personObject.age+"</td></tr>")
})
$("#displayArrayDataHere").append("</table>");
}
I am fairly new to javascript and not really sure what I am doing. Right now I am trying to add textbox data as well as some strings to cookies to display on another page. The textbox part is working.
For the strings, I am taking the value of a radio button (for a multiple choice quiz validation) and if the value is the correct value for that group, I would like to add a string to cookies. I can't figure out what I am doing wrong for this part.
Specifically what isn't working is the content in the gradeit() function
JS file
var total = 5;
var right = 0;
//cookies
function addToCookie(id, value)
{
document.cookie = id + escape(value);
}
var grade=new Array()
function gradeit(){
if(document.getElementById('correctOne').checked)
{
right++;
addToCookie("Q1 - Correct",right);
}
else {addToCOokie("Q1 - Incorrect", right);}
}
function checkCookie() {
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
var email = document.getElementById("email").value;
addToCookie("First Name= ",firstName);
addToCookie("Last Name= ",lastName);
addToCookie("Email=",email);
}
window.onload = function () {
var elem = document.getElementById("submit");
elem.addEventListener('click', checkCookie);
}
// determine whether there is a cookie
var allcookies = document.cookie;
alert("All Cookies : " + allcookies);
// Get all the cookies pairs in an array
cookiearray = allcookies.split(';');
var result = "";
// Now take key value pair out of this array
for (var i = 0; i < cookiearray.length; i++) {
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
result +=( name + " is : " + value)+"<br>";
}
document.writeln(result);
HTML PAge
<DOCTYPE HTML5>
<html>
<head>
<meta charset="utf-8">
<title>Quiz</title>
<script src="cookies.js" type="text/javascript"></script>
</head>
<body>
<h1><b>Multiple Choice Quiz</b></h1>
<form name="myquiz" action="answers.html" method="post">
<h2>Please Enter the Following:</h2>
First Name: <input type="text" id="fname"></input>
Last Name: <input type="text" id="lname"></input><br><br>
Student Email: <input type="email" id="email"></input>
<br>
<h3>#1. What is the capital of Iowa?</h3>
<input type="radio" name="question1" id="correctOne">Des Moines</input>
<input type="radio" name="question1" id="wrong">Los Angeles</input>
<input type="radio" name="question1" id="wrong">Paris</input>
<input type="radio" name="question1" id="wrong">Tokyo</input>
<br><br>
<input type="submit" id="submit" value="Submit Answers" onClick="gradeit()"></input>
</form>
</body>
</html>
I just got it to work by modifying my gradeit() function this way:
function gradeit(){
var ans = "";
if(document.getElementById('correctOne').checked)
{
//document.getElementById("output").innerHTML = "Q1 - Correct";
right++;
ans ="Right";
addToCookie("Q1 - ", ans);
}
else {
ans ="Wrong";
addToCookie("Q1 - ", ans);
}
}
first of all I'm sorry if this is a long code segment however, I'm trying to make a modal window which writes the thing you wrote in my user form and asks you to confirm it. I am currently in a class to learn Javascript and I'm not allowed to use innerHTML and I must write the "Firstname:" etc dynamically (the text for firstname) and am not allowed to just write it inside the popup window. I've gotten most stuff to work but the "Firstname:" "Lastname" etc comes up as "undefined" or (as you can see the thing I tried with just the first name in this case) comes up as "null".
Hopefully someone can shed some light on this subject for me, this is the HTML:
<form action="http://voyager.lnu.se/tekinet/kurser/dtt/wp_webbteknik/process_form.php" method="POST" id="userform" target="_blank">
<p id="formQuestion1">Förnamn</p>
<div id="error1"></div>
<input type="text" name="firstName" id="test"/>
<p id="formQuestion2">Efternamn</p>
<div id="error2"></div>
<input type="text" name="lastName" />
<p id="formQuestion3">Postnummer</p>
<div id="error3"></div>
<input type="text" name="postCode" id="codeText"/>
<p id="formQuestion4">E-post</p>
<div id="error4"></div>
<input type="text" name="eMail" />
<br />
<br />
<label id="model" class="formQuestion" for="priceModel">Prismodell</label>
<br />
<select name="Type" id="priceModel">
<option value="Låg" selected>Låg</option>
<option value="Medel">Medel</option>
<option value="Hög">Hög</option>
</select>
<br />
<br />
<br />
<input id="sendButton" type="submit" value="Genomför Köp" />
</form>
And here is the segment for the modal window (Javascript)
function popup(backgroundDiv) {
var popForm = document.getElementById("userform");
var myDiv = document.createElement("div");
myDiv.className = "popupWindow";
var priceModel = document.getElementById("priceModel");
// Knappar
var newButton = document.createElement("button");
var newerButton = document.createElement("button");
newButton.setAttribute("value", "Skicka");
newButton.innerHTML = "Skicka"; // Here I actually use innerHTML because I don't know
newerButton.innerHTML = "Stäng"; // any other way to set the text inside the button
newButton.className = "popupButton";
newerButton.className = "popupButton";
newButton.setAttribute("id", "Skicka");
newerButton.setAttribute("id", "Avbryt");
myDiv.appendChild(newButton);
myDiv.appendChild(newerButton);
// Information
var h1 = document.createElement("h1");
h1.setAttribute("id", "popuph1");
var h1Text = document.createTextNode("Vänligen kontrollera dina uppgifter");
var text = document.getElementById("formQuestion1");
var writeFname = text.nodeValue + popForm.elements.firstName.value;
var writeLname = document.getElementById("formQuestion2").value + popForm.elements.lastName.value;
var writeCode = document.getElementById("formQuestion3").value + popForm.elements.postCode.value;
var writeMail = document.getElementById("formQuestion4").value + popForm.elements.eMail.value;
var writePlan = document.getElementById("model").value + priceModel.value;
var p1 = document.createTextNode(writeFname);
var p2 = document.createTextNode(writeLname);
var p3 = document.createTextNode(writeCode);
var p4 = document.createTextNode(writeMail);
var p5 = document.createTextNode(writePlan);
h1.appendChild(h1Text);
myDiv.appendChild(h1);
myDiv.appendChild(p1);
myDiv.appendChild(document.createElement('br'));
myDiv.appendChild(p2);
myDiv.appendChild(document.createElement('br'));
myDiv.appendChild(p3);
myDiv.appendChild(document.createElement('br'));
myDiv.appendChild(p4);
myDiv.appendChild(document.createElement('br'));
myDiv.appendChild(p5);
document.body.appendChild(myDiv);
newButton.onclick = function () {
document.body.removeChild(myDiv);
document.body.removeChild(backgroundDiv);
return true;
};
If you don't want to use innerHTML then you can use those options, suppose you want value from this node <p id="formQuestion1">Förnamn</p>
Then your code would be
var dom = document.getElementById('formQuestion1');
1) var res = dom.innerText;
OR
2) var res = dom.textContent;
OR
3) var res = dom.firstChild.nodeValue;