javascript Using cookie to pass variables to another page - javascript

I'm using javascript for the first time and am trying to pass variables to another page via a cookie. However it doesn't appear to be working. Right now I'm just trying to check the cookie value using an alert box. I've looked but haven't been able to find anything that can help me figure out what's going wrong. I was originally trying to implement the solution from this page: How to use JavaScript to fill a form on another page
Any help is appreciated.
My code for the first page is:
<!DOCTYPE html>
<html lang="en">
<!--Matt Proctor -->
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<link rel="stylesheet/less" type="text/css" href="dealership.less">
<script src="less.js" type="text/javascript"></script>
</head>
<body>
<script>
//validate name
function checkName() {
var lastN = document.getElementById('lName').value;
var firstN = document.getElementById('fName').value;
if (lastN == "" || firstN == "" || (/[^A-Za-z]/.test(lastN)) || (/[^A-Za-z]/.test(firstN))) {
window.alert("Please enter ONLY alphabetical characters for First Name AND Last Name");
return false;
}
else{
return true;
}
}
//check if q1 answered
function checkQ1() {
if (document.getElementById('timeButton1').checked == false
&& document.getElementById('timeButton2').checked == false
&& document.getElementById('timeButton3').checked == false
&& document.getElementById('timeButton4').checked == false
&& document.getElementById('timeButton5').checked == false) {
window.alert("Please answer question 1");
return false;
}
else{
return true;
}
}
//check if q2 answered
function checkQ2() {
if (document.getElementById('vehicleButton1').checked == false
&& document.getElementById('vehicleButton2').checked == false
&& document.getElementById('vehicleButton3').checked == false
&& document.getElementById('vehicleButton4').checked == false
&& document.getElementById('vehicleButton5').checked == false
&& document.getElementById('vehicleButton6').checked == false
&& document.getElementById('vehicleButton7').checked == false
&& document.getElementById('vehicleButton8').checked == false
&& document.getElementById('vehicleButton9').checked == false
&& document.getElementById('vehicleButton10').checked == false
&& document.getElementById('vehicleButton11').checked == false) {
window.alert("Please answer question 2");
return false;
}
else{
return true;
}
}
//validate q3
function checkQ3() {
var min = document.getElementById('minPriceText').value;
var max = document.getElementById('maxPriceText').value;
if (min == "" || (/[^0-9]/.test(min)) || max == "" || (/[^0-9]/.test(max))) {
window.alert("Please enter a numerical value for both the minimum price and maximum price");
return false;
}
else{
return true;
}
}
//check q4 answered
function checkQ4() {
if (document.getElementById('problemsNo').checked == false
&& document.getElementById('problemsYes').checked == false) {
window.alert("Please answer question 4");
return false;
}
else {
return true;
}
}
//check q5 answered
function checkQ5() {
if (document.getElementById('cleanNo').checked == false
&& document.getElementById('cleanYes').checked == false) {
window.alert("Please answer question 5")
return false;
}
else {
return true
}
}
//check q6 answered
function checkQ6() {
if (document.getElementById('gasNo').checked == false
&& document.getElementById('gasYes').checked == false) {
window.alert("Please answer question 6")
return false;
}
else {
return true;
}
}
//check q7 answered
function checkQ7() {
if (document.getElementById('experience1').checked == false
&& document.getElementById('experience2').checked == false
&& document.getElementById('experience3').checked == false
&& document.getElementById('experience4').checked == false
&& document.getElementById('experience5').checked == false
&& document.getElementById('experience6').checked == false
&& document.getElementById('experience7').checked == false
&& document.getElementById('experience8').checked == false
&& document.getElementById('experience9').checked == false
&& document.getElementById('experience10').checked == false) {
window.alert("Please answer question 7")
return false;
}
else {
return true;
}
}
//check if all data correct, and then attempt to pass to another webpage via cookie.
function checkAndPass() {
var nameCorrect, q1Correct, q2Correct, q3Correect, q4Correct, q5Correct, q6Correct, q7Correct;
nameCorrect = checkName();
q1Correct = checkQ1();
q2Correct = checkQ2();
q3Correct = checkQ3();
q4Correct = checkQ4();
q5Correct = checkQ5();
q6Correct = checkQ6();
q7Correct = checkQ7();
if(nameCorrect==true &&
q1Correct==true &&
q2Correct==true &&
q3Correct==true &&
q4Correct==true &&
q5Correct==true &&
q6Correct==true &&
q7Correct==true) {
var name = document.getElementById('fName').value + " " + document.getElementById('lName').value;
var quest1 = document.querySelector('input[name = "Q1"]:checked').value;
var quest2 = document.querySelector('input[name = "Q2"]:checked').value;
var quest3 = document.getElementById('minPriceText').value + "-" + document.getElementById('maxPriceText').value;
var quest4 = document.querySelector('input[name = "Q4"]:checked').value;
var quest5 = document.querySelector('input[name = "Q5"]:checked').value;
var quest6 = document.querySelector('input[name = "Q6"]:checked').value;
var quest7 = document.querySelector('input[name = "Q7"]:checked').value;
var commentline = document.getElementById('comments').value;
document.cookie=name + "," + quest1 + "/" + quest2 + "/" + quest3 + "/" + quest4 + "/" + quest5 "/" + quest6 + "/" + quest7 + "/" + commentline + "; path=/lab5summary.html";
newSummary();
}
}
function newSummary() {
window.open('lab5summary.html',
'_blank');
}
</script>
<img class="displaycenter" src="AcuraLogo.png" alt="Acura Logo">
<h1 align ="center">After Purchase Customer Survey</h1>
<div class="customer">
<h4>Customer Information</h4>
<br>
<br>
First name:<br>
<input id="fName" type="text" name="firstname" value="">
<br>
Last name:<br>
<input id="lName" type="text" name="lastname" value="">
</div>
<br><br>
<!--Question 1 asking about how long a customer had to wait before an employee assisted them-->
<div class="border">
<p> Q1: What was your approximate wait time before an associate was available to assist you?</p>
<input id="timeButton1" type="radio" class ="larger" name="Q1" value=".25">15 minutes or less.
<input id="timeButton2" type="radio" class ="larger" name="Q1" value=".5">30 minutes.
<input id="timeButton3" type="radio" class ="larger" name="Q1" value=".75">45 minutes.
<input id="timeButton4" type="radio" class ="larger" name="Q1" value="1">1 hour.
<input id="timeButton5" type="radio" class ="larger" name="Q1" value="1.5">1 and 1/2 hours or more.
<p> Q2: What kind of vehicle(s) were you looking for?</p>
<input id="vehicleButton1" type="checkbox" class ="larger" name="Q2" value="Sedan"> Sedan
<input id="vehicleButton2" type="checkbox" class ="larger" name="Q2" value="SUV/Crossover"> SVU/Crossover
<input id="vehicleButton3" type="checkbox" class ="larger" name="Q2" value="Convertible"> Convertible
<input id="vehicleButton4" type="checkbox" class ="larger" name="Q2" value="Coupe"> Coupe
<input id="vehicleButton5" type="checkbox" class ="larger" name="Q2" value="Hatchback"> Sedan
<input id="vehicleButton6" type="checkbox" class ="larger" name="Q2" value="Hybrid/Electric"> Hybrid/Electric
<input id="vehicleButton7" type="checkbox" class ="larger" name="Q2" value="Luxury"> Luxury
<input id="vehicleButton8" type="checkbox" class ="larger" name="Q2" value="Van/Minivan"> Van/Minivan
<input id="vehicleButton9" type="checkbox" class ="larger" name="Q2" value="Truck"> Truck
<input id="vehicleButton10" type="checkbox" class ="larger" name="Q2" value="Wagon"> Wagon
<input id="vehicleButton11" type="checkbox" class ="larger" name="Q2" value="AWD/4WD"> AWD/4WD
<p> Q3: What price range were looking for in a vehicle? </p>
Minimum: $
<input id="minPriceText" type="text" name="minprice" value="">
Maximum: $
<input id="maxPriceText" type="text" name="minprice" value="">
<p> Q4: Did the vehicle(s) purchased have any problems?</p>
<input id="problemsNo" type="radio" class ="larger" name="Q4" value="Yes">Yes
<input id="problemsYes" type="radio" class ="larger" name="Q4" value="No">No
<p> Q5: Was the interior of the vehicle clean? </p>
<input id="cleanYes" type="radio" class ="larger" name="Q5" value="Yes">Yes
<input id="cleanNo" type="radio" class ="larger" name="Q5" value="No">No
<p> Q6: Did the vehicle come with a full tank of gas? </p>
<input id="gasYes" type="radio" class ="larger" name="Q6" value="Yes">Yes
<input id="gasNo" type="radio" class ="larger" name="Q6" value="No">No
<p> Q7: On the scale from 1 to 10, 1 being extremely unpleasant and
10 being absolutely perfect, how would you rate your overall experience? </p>
<input id="experience1" type="radio" class ="larger" name="Q7" value="1">1
<input id="experience2" type="radio" class ="larger" name="Q7" value="2">2
<input id="experience3" type="radio" class ="larger" name="Q7" value="3">3
<input id="experience4" type="radio" class ="larger" name="Q7" value="4">4
<input id="experience5" type="radio" class ="larger" name="Q7" value="5">5
<input id="experience6" type="radio" class ="larger" name="Q7" value="6">6
<input id="experience7" type="radio" class ="larger" name="Q7" value="7">7
<input id="experience8" type="radio" class ="larger" name="Q7" value="8">8
<input id="experience9" type="radio" class ="larger" name="Q7" value="9">9
<input id="experience10" type="radio" class ="larger" name="Q7" value="10">10
<p> Finally please feel free to leave any other comments about your purchase/purchase-process below: </p>
<input id="comments" type="textbox" name="comments" value="" size="100">
</div>
<br>
<br>
<input onclick="checkAndPass()" id="submitButton" class="button1" type="submit" value="Submit">
</body>
</html>
The code of the page I'm passing to is:
<!DOCTYPE html>
<html lang="en">
<!--Matt Proctor -->
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<link rel="stylesheet/less" type="text/css" href="dealership.less">
<script src="less.js" type="text/javascript"></script>
</head>
<body>
<script>
var COOKIES = {};
var cookieStr=document.cookie;
window.alert("Cookie: " + cookieStr);
</script>
<img class="displaycenter" src="AcuraLogo.png" alt="Acura Logo">
<h1 align ="center">After Purchase Customer Survey Summary</h1>
<div class="border">
<p> Q1: What was your approximate wait time before an associate was available to assist you?</p>
<p> Q2: What kind of vehicle(s) were you looking for?</p>
<p> Q3: What price range were looking for in a vehicle? </p>
Minimum: $
Maximum:
<p> Q4: Did the vehicle(s) purchased have any problems?</p>
<p> Q5: Was the interior of the vehicle clean? </p>
<p> Q6: Did the vehicle come with a full tank of gas? </p>
<p> Q7: On the scale from 1 to 10, 1 being extremely unpleasant and
10 being absolutely perfect, how would you rate your overall experience? </p>
<p> Finally please feel free to leave any other comments about your purchase/purchase-process below: </p>
</div>
</body>
</html>
Also, for some reason firefox web console seems to think I need to place a semi-colon here in the first page after quest5:
document.cookie=name + "," + quest1 + "/" + quest2 + "/" + quest3 + "/" + quest4 + "/" + quest5 "/" + quest6 + "/" + quest7 + "/" + commentline + "; path=/lab5summary.html";
As a final note, I can only use javascript for this, not jQuery or PHP.

In your example is missing a plus sign:
+ quest5+"/" + quest6
Cookies are bound by a domain, so if you open from your file system (e.g file://index.html), it won't work.
If you are on modern browsers, I suggest you use localStorage and sessionStorage.
sessionStorage lasts as long as the page is open and localStorage until the browser's cache be cleaned.

You can also use store.js
Store.js
And you also probably want to expurge your code by using objects and arrays for ids and variables.

Related

JS function resets after completion

I have a small form designed to calculate a score based on the answers given. Everything works, the variables are shown in the variables and also shown in the html for a split second. However, after a split second, the function resets and the resulting var is also removed. In trying to understand, I think it has to do with the scope of the var or form behavior? Here is a snippet:
</head>
<body>
<form id="calculateChangeForm" name="calculateChangeForm">
<p><strong>1. To what extend does the change impact the organization?</strong></p>
<input id="q1a1" name="q1" type="radio" value="2"> <label for="q1a1">A specific department or a working group</label><br><input id="q1a2" name="q1" type="radio" value="6"> <label for="q1a2">One department </label><br><input id="q1a3" name="q1" type="radio" value="7"> <label for="q1a3">Several departments</label><br><input id="q1a4" name="q1" type="radio" value="8"> <label for="q1a4">Whole organization</label><br><input id="q1a5" name="q1" type="radio" value="8"> <label for="q1a5">Cross entities</label><br><input id="q1a6" name="q1" type="radio" value="9"> <label for="q1a6">Regional Impact</label><br><input id="q1a7" name="q1" type="radio" value="10"> <label for="q1a7">Group Impact</label><hr class="mb-5 mt-5">
<p><strong>2. How many employees are impacted? </strong></p>
<input id="q2a1" name="q2" type="radio" value="1"> <label for="q2a1"> < 10 </label><br><input id="q2a2" name="q2" type="radio" value="4"> <label for="q2a2">10 - 50 </label><br><input id="q2a3" name="q2" type="radio" value="7"> <label for="q2a3">51 - 100</label><br><input id="q2a4" name="q2" type="radio" value="8"> <label for="q2a4">101 - 200</label><br><input id="q2a5" name="q2" type="radio" value="9"> <label for="q2a5">201 - 500</label><br><input id="q2a6" name="q2" type="radio" value="10"> <label for="q2a6"> > 500 </label><br><br><button id="calculateChangeButton" class="button">Submit</button>
<script> document.getElementById("calculateChangeButton").onclick = function() {calculateChange();}; </script>
</form><hr class="mb-5 mt-5"></div>
<p>Your score is: <span id="changeScore"></span></p>
<script>
var changescore = 0;
function calculateChange(){
var val1 = 0;
for( i = 0; i < document.calculateChangeForm.q1.length; i++ ){
if( document.calculateChangeForm.q1[i].checked == true ){
val1 = document.calculateChangeForm.q1[i].value;
alert("The value of Question 1 answer is: " + val1);
}
}
var val2 = 0;
for( i = 0; i < document.calculateChangeForm.q2.length; i++ ){
if( document.calculateChangeForm.q2[i].checked == true ){
val2 = document.calculateChangeForm.q2[i].value;
alert("The value of Question 2 answer is: " + val2);
}
}
var changescore = parseInt(val1) + parseInt(val2);
alert("The total score: " + changescore);
document.getElementById("changeScore").innerHTML = changescore;
}
</script>
</body>
Thank you,
After input from user t348575, it was clear that the button should be changed to a an input type="button" in order to stop the form from being submitted:

EPUB Score catching

I created an EPUB through Adobe InDesign CC. After exporting the project to EPUB i extracted the file so that I can insert a (html, javascript) page for the exercises. Could somebody please help how can I manage to throw a value from the epub (probably the score) to a website if online and store the value(score) inside the epub when offline.
<form action="#" method="post">
<section id="1" epub:type="item">
<p>1. smile - smiled <label id="checker" style="color:red"></label></p>
<input type="radio" id="myRadio" name="c1" value="1" />
<label>YES</label>
<input type="radio" id="myRadio" name="c1" value="0" />
<label>NO</label><br/>
</section>
<section id="2" epub:type="item">
<p>2. dance - danced <label id="checker2" style="color:red"></label></p>
<input type="radio" id="myRadio2" name="c2" value="1" />
<label>YES</label>
<input type="radio" id="myRadio2" name="c2" value="0" />
<label>NO</label><br/>
</section>
<section id="3" epub:type="item">
<p>3. rise - rised <label id="checker3" style="color:red"></label></p>
<input type="radio" id="myRadio3" name="c3" value="1" />
<label>YES</label>
<input type="radio" id="myRadio3" name="c3" value="0" />
<label>NO</label><br/>
</section>
</div>
</form>
Heres the javascript:
temp = 0;
if (getRadioVal( document.getElementById('demoForm'), 'c1' ) === "1") {
temp = temp + 1;
} else{
document.getElementById('checker').innerHTML = "| wrong";
}
if (getRadioVal( document.getElementById('demoForm'), 'c2' ) === "1") {
temp = temp + 1;
} else{
document.getElementById('checker2').innerHTML = "| wrong";
}
if (getRadioVal( document.getElementById('demoForm'), 'c3' ) === "0") {
temp = temp + 1;
} else{
document.getElementById('checker3').innerHTML = "| wrong";
}
document.getElementById("score").innerHTML = temp;
This question has been discussed in some Adobe Forum and the answer seems like you can't: https://forums.adobe.com/thread/1939249

Making javascript check what radio form has been selected

I am trying to make a dog race.
Basically what I want is to check what radio the user checked,
compare it to a random number between 1 - 5 and see if he won.
My question is... How do I compare them?
This is my code so far.
function chooser(){
var theDogs = ["dog1","dog2","dog3","dog4","dog5"],
rand = theDogs[Math.floor(Math.random() * theDogs.length)];
document.getElementById("winner").innerHTML = rand;
if(pick == rand)
{document.getElementById("winner").innerHTML =("win!");}
else {
document.getElementById("winner").innerHTML =("loose");
}
}
HTML:
<form id="pick" action="rand">
<input type="radio" name="dog" id="dog1">Dog1<br>
<input type="radio" name="dog" id="dog2">Dog2<br>
<input type="radio" name="dog" id="dog3">Dog3<br>
<input type="radio" name="dog" id="dog4">Dog4<br>
<input type="radio" name="dog" id="dog5">Dog5<br>
</form>
<br>
<br>
<input type="submit" value="Gamble" onclick="chooser();">
<br>
<p id="winner"> </p>
A jQuery and Native JavaScript Approach. Take your pick.
$("#submitjq").click(function() {
var theDogs = ["dog1","dog2","dog3","dog4","dog5"],
rand = theDogs[Math.floor(Math.random() * theDogs.length)];
var pick = $("input[type=radio][name='dog']:checked").val();
if(pick == rand)
{
$("#winner").html("jQuery: Won!");
}
else {
$("#winner").html("jQuery: Lost!");
}
});
document.getElementById('submitjs').onclick = function () {
var theDogs = ["dog1","dog2","dog3","dog4","dog5"],
rand = theDogs[Math.floor(Math.random() * theDogs.length)];
var pick = document.pick.dog.value;
console.log(pick);
if(pick == rand)
{
document.getElementById("winner").innerHTML = "JavaScript: Won!" ;
}
else {
document.getElementById("winner").innerHTML = "JavaScript: Lost!" ;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="pick" name="pick" action="rand">
<input type="radio" name="dog" value="dog1">Dog1<br>
<input type="radio" name="dog" value="dog2">Dog2<br>
<input type="radio" name="dog" value="dog3">Dog3<br>
<input type="radio" name="dog" value="dog4">Dog4<br>
<input type="radio" name="dog" value="dog5">Dog5<br>
</form>
<br>
<br>
<input type="submit" id="submitjs" value="Gamble Native JavaScript" />
<input type="submit" id="submitjq" value="Gamble jQuery" />
<br>
<p id="winner"> </p>
You need to give each radio button a value, and then getElementsByName, iterating through to find the one that's checked. See similar thread...

Creating a multiple choice option in javascript

I have created an HTML multiple choice question. I am facing a problem how to validate it. Below is the HTML code:
<h1>JavaScript is ______ Language.</h1><br>
<form>
<input type="radio" name="choice" value="Scripting"> Scripting
<input type="radio" name="choice" value="Programming"> Programming
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
</form>
<button>Submit Answer</button>
When the user clicks the submit button, there should be an alert that will show a message based on what was selected.
If no option was selected, the alert box should say "please select choice answer".
If the "Scripting" option was selected, the alert box should say "Answer is correct !"
If an option different from "Scripting" is selected, the alert box should say "Answer is wrong".
I want to create this validation in JavaScript.
You have to use onclick attribute and more js
attach event hander to your button
get radio elements value
compare
var submitAnswer = function() {
var radios = document.getElementsByName('choice');
var val= "";
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
val = radios[i].value;
break;
}
}
if (val == "" ) {
alert('please select choice answer');
} else if ( val == "Scripting" ) {
alert('Answer is correct !');
} else {
alert('Answer is wrong');
}
};
<h1>JavaScript is ______ Language.</h1><br>
<form >
<input type="radio" name="choice" value="Scripting"> Scripting
<input type="radio" name="choice" value="Programming"> Programming
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
</form>
<button onclick="submitAnswer()">Submit Answer</button>
var submitAnswer = function() {
var radios = document.getElementsByName('choice');
var val= "";
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
val = radios[i].value;
break;
}
}
if (val == "" ) {
alert('please select choice answer');
} else if ( val == "Scripting" ) {
alert('Answer is correct !');
} else {
alert('Answer is wrong');
}
};
<h1>JavaScript is ______ Language.</h1><br>
<form >
<input type="radio" name="choice" value="Scripting"> Scripting
<input type="radio" name="choice" value="Programming"> Programming
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
</form>
<button onclick="submitAnswer()">Submit Answer</button>
Some changes
I made some changes to the code above to make it more 'abstract'
<h1>JavaScript is ______ Language.</h1><br>
<form id="d1">
<input type="radio" name="choice" value="Scripting"> Scripting
<input type="radio" name="choice" value="Programming"> Programming
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
</form>
<button onclick="submitAnswer(d1.choice.value, 'Scripting')">Submit Answer</button>
<script>
var submitAnswer = function(valore, rightanswer) {
if (valore == rightanswer) {
alert("OK");
}
};
</script>
Another, more complex example
<div style="background-color:lightblue">
<h1>JavaScript is a <span id='a1'>______</span> Language.</h1><br>
<form id="d1">
<input type="radio" name="choice" value="Scripting"> Scripting
<input type="radio" name="choice" value="Programming"> Programming
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
<br>
<input type="submit" value="submit" onclick="validate(choice.value, 'Scripting', 'd1','a1')">
</form>
</div>
<div style="background-color:lightblue">
<h1>Python is a <span id='a2'>______</span> Language.</h1><br>
<form id="d2">
<input type="radio" name="choice" value="Scripting"> Scripting
<input type="radio" name="choice" value="Wonderful"> Wonderful
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
<br>
<input type="submit" value="submit" onclick="validate(choice.value, 'Wonderful', 'd2', 'a2')">
</form>
</div>
<script>
var validate = function(valore, rightanswer, form, span) {
var formname = document.getElementById(form)
var spanname = document.getElementById(span)
spanname.innerHTML = rightanswer;
if (valore == rightanswer) {
formname.innerHTML ="<div style='background-color:lightgreen'><h1>GREAT! YOU'RE RIGHT: The answer, in fact, was: " + rightanswer + "</h1></div>";
}
else {
formname.innerHTML ="<div style='background-color:pink'><h1>Sorry, you where wrong: The answer was: " + rightanswer + "</h1></div>";
}
};
</script>
Use the required keyword. This prompts the user to choose a value, when the submit button is pressed without choosing any option. And always prefer to use
<input type="submit" value="submit"> over <button>Submit Answer</button>
while handling forms. Use the onclick() event handler to call your Javascript code.
<h1>JavaScript is ______ Language.</h1><br>
<form >
<input type="radio" name="choice" value="Scripting" required> Scripting
<input type="radio" name="choice" value="Programming"> Programming
<input type="radio" name="choice" value="Application"> Application
<input type="radio" name="choice" value="None of These"> None of These
<input type="submit" value="submit" onclick="validate()">
</form>
And the javascript part is as follows.
<script type="text/javascript">
function validate() {
var a= document.getElementByName("choice");
for (var i = 0, i < a.length; i++) {
if (a[i].checked) {
if( a[i].value == "scripting" )
alert("your answer is correct");
else
alert("your answer is not correct");
break;
} } }
</script>
Here condition is showing in alert pop up box. but I want to show it in a html tag.
But after clicking submit button, innerHTML content showing a millisecond and then automatic remove the content. How selection will stay in innerHTML
document.getElementById("answer").innerHTML;
var submitAnswer = function() {
var radios = document.getElementsByName('choice');
var val= "";
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
val = radios[i].value;
break;
}
}
if (val == "" ) {
document.getElementById("answer").innerHTML = "please select choice answer";
} else if ( val == "Scripting" ) {
document.getElementById("answer").innerHTML = "Answer is correct !"
} else {
document.getElementById("answer").innerHTML = "Answer is wrong"
}
};
You can add a function and event onClick so that whenever someone clicks on option submit button will appear.

Checking empty form elements in javascript

I'm making a simple client-side, self-grading quiz.
I ask 6 questions and I want to alert the user with their score (keeping things simple). If they leave an answer blank, an alert will appear.
I'm new to javascript and don't really know how to check individual form elements to see if they're empty. I'm also having problems with getting my code to run.
JS
EDIT
function grade() {
var score = 0;
var elt = document.quiz;
// Check to see if no questions were left unanswered.
if elt.question1.value.length == 0 || elt.question2.value.length == 0 ||
elt.question3.value.length == 0 || elt.question4.value.length == 0 ||
elt.question5.value.length == 0 || elt.question6.value.length == 0
{
alert ("Whoops, you're missing an answer!")
}
if (elt.question1[1].checked) {
score += 1;
}
if (elt.question2[0].checked) {
score += 1;
}
if (elt.question3[0].checked == false && elt.question3[1].checked &&
elt.question3[2].checked == false && elt.question3[3].checked == false) {
score += 1;
}
if (elt.question4[0].checked == false && elt.question4[1].checked == false &&
elt.question4[2].checked == false && elt.question4[3].checked) {
score += 1;
}
elt.question5 = elt.question5.toLowerCase()
if (elt.question5.value != '' && elt.question5.value.indexOf('galaxy') != -1) {
score += 1;
}
elt.question6 = elt.question6.toLowerCase()
if (elt.question5.value != '' && elt.question6.value.indexOf('age') != -1) {
score += 1;
}
score = score / 6 * 100;
score = score.toFixed(2);
alert("You scored " + score + "%");
return false; // Return true if you want the form to submit on validation/grade
}
You have a some significant errors in your markup:
Do not wrap a form element around each question. These should all be in one form element. (Also, each question be in a OL to number the question in series.)
You're not properly closing all of your label's, so they're selecting other elements when you click them (try question 3, first checkbox).
You need the grade() function on the form's submit handler, and it needs to be onsubmit="return grade()", with grade() returning false when it doesn't "pass" to prevent form submission*.
* Note, I set the grade() function to always return false in the example. You would need to add the logic for when it would allow the form to submit.
As far as the Javascript...
You need the elt variable to be equal to your document.quiz (note, I changed the main form to have a name="quiz" in your markup). You can use indexOf() instead of a regex if you just want to have a simple check (regex could check for age as a word, though).
If you just want to make sure a text input is not empty, you can use el.value.length != 0 or el.value != ''.
Also, looking at your grading code, if you want only one to be selected, you could use a radio, unless you want the person taking the quiz to not know if one or more were valid answers. But radio's only allow you to select a single value.
HTML
<h3> Self-Grading Astronomy Quiz </h3>
<form action="" name="quiz" onsubmit="return grade();">
<p>1. According to Kepler the orbit of the earth is a circle with the sun at the center.</p>
<p>
<label><input type="radio" name="question1" value="true" /> True </label>
<label><input type="radio" name="question1" value="false" /> False </label>
</p>
<p>2. Ancient astronomers did consider the heliocentric model of the solar system but rejected it because they could not detect parallax.</p>
<p>
<label><input type="radio" name="question2" value="true" /> True </label>
<label><input type="radio" name="question2" value="false" /> False </label>
</p>
<p>3. The total amount of energy that a star emits is directly related to its:</p>
<p>
<label><input type="checkbox" name="question3" value="1" /> a) surface gravity and magnetic field </label><br/>
<label><input type="checkbox" name="question3" value="2" /> b) radius and temperature </label><br/>
<label><input type="checkbox" name="question3" value="3" /> c) pressure and volume </label><br/>
<label><input type="checkbox" name="question3" value="4" /> d) location and velocity </label>
</p>
<p>4. Stars that live the longest have:</p>
<p>
<label><input type="checkbox" name="question4" value="1" /> a) high mass </label><br/>
<label><input type="checkbox" name="question4" value="2" /> b) high temperature </label><br/>
<label><input type="checkbox" name="question4" value="3" /> c) lots of hydrogen </label><br/>
<label><input type="checkbox" name="question4" value="4" /> d) small mass </label>
</p>
<p>5. A collection of a hundred billion stars, gas, and dust is called a __________.</p>
<p>
<input type='text' id='question5' />
</p>
<p>6. The inverse of the Hubble's constant is a measure of the __________ of the universe.</p>
<p>
<input type='text' id='question6' />
</p>
<p>
<input type='button' onclick='grade()' value='Grade' />
</p>
</form>
Javascript
function grade() {
//**Would I do something like this?
//if(elem.value.length == 0){
// alert("Whoops, looks like you didn't answer a question.")}
var score = 0;
var elt = document.quiz;
if (elt.question1[1].checked) {
score += 1;
}
if (elt.question2[0].checked) {
score += 1;
}
if (elt.question3[0].checked == false && elt.question3[1].checked && elt.question3[2].checked == false && elt.question3[3].checked == false) {
score += 1;
}
if (elt.question4[0].checked == false && elt.question4[1].checked == false && elt.question4[2].checked == false && elt.question4[3].checked) {
score += 1;
}
if (elt.question5.value != '' && elt.question5.value.indexOf('galaxy') != -1) {
score += 1;
}
if (elt.question5.value != '' && elt.question6.value.indexOf('age') != -1) {
score += 1;
}
score = score / 6 * 100;
score = score.toFixed(2);
alert("You scored " + score + "%");
return false; // Return true if you want the form to submit on validation/grade
}
http://jsfiddle.net/BeD3Z/10/
check individual form elements to see if they're empty
You just compare the value to an empty string:
if(elt.question6.value == '') {
alert('Unanswered');
}
You can use jquerys built in validation http://docs.jquery.com/Plugins/validation. It has built in functionality to check for required and to display an error message below the field which is blank.

Categories

Resources