I am building a quiz, I have constructed the database (I will input an example of what my tables look like below. I am having an issue getting the user's answers to actually be placed in the database? Right now, I can load the quiz on my browser, answer the questions, but I cannot actually figure out my score on the quiz.
Database
questions
ID question
1 Question1?
2 Question2?
etc
choices
ID questID answer
1 1 Ansa
2 1 Ansb
3 1 Ansc
1 2 Ansa
2 2 Ansb
3 2 Ansc
4 2 Ansd
etc
userans
userID questID answerID
right now userans table is empty because that is where the user's answers are supposed to be put
My quiz is pretty simple, but I just need help getting the database & quiz to "talk" to each other.
Any help is appreciated!
Quiz code
<!DOCTYPE html>
<html>
<head>
<title>Quiz</title>
<script language="Javascript">
function process()
{
var A = 0;
var B = 0;
var C = 0;
var D = 0;
var f = document.f;
var i = 0;
for (i = 0; i < f.q1.length; i++) if (f.q1[i].checked) value = f.q1[i].value;
if (value == "13") { }
if (value == "11") { C++; A++; B++; }
if (value == "5") { C++; D++; A++; B++; }
for (i = 0; i < f.q2.length; i++) if (f.q2[i].checked) value = f.q2[i].value;
if (value == "5") { C++; D++; A++; B++; }
if (value == "12") { D++; A++; B++; }
if (value == "11") { C++; A++; B++; }
if (value == "10") { C++; D++; A++; }
/*Copy the above for loop for all subsequent questions, if needed*/
var out = "A";
i = "a";
if (C > i) { out ="C"; i = "c"; }
if (B > i) { out ="B"; i = "b"; }
if (D > i) { out ="D"; i = "d"; }
window.alert ("Result: " + i + " !!");
}
</script>
</head>
<body>
<?php include ('Menu2.html'); ?>
<p>Answer the questions below</p> <br>
<form name="f">
<b>Question1<br></b>
<input type="radio" name="q1" value="1">Ansa<br>
<input type="radio" name="q1" value="2">Ansb<br>
<input type="radio" name="q1" value="3">Ansc<br><br>
<b>Question2<br></b>
<input type="radio" name="q2" value="1">Ansa<br>
<input type="radio" name="q2" value="2">Ansb<br>
<input type="radio" name="q2" value="3">Ansc<br>
<input type="radio" name="q2" value="4">Ansd<br><br>
/*Input more questions, if needed, here*/
Thanks for taking the quiz! <br>
<input type="button" value="Score!" onclick="process();"><br><br>
</form>
</body>
</html>
Javascript is a client side language - in order to connect to a database, you'll need to use server side software such as PHP. Your HTML form can submit content via GET or POST, or you can use Ajax to push/pull information, but cannot be done via Javascript.
Check out some examples:
Can JavaScript connect with MySQL?
How can I use jQuery to run MySQL queries?
Related
Updated with entire code for context
My code should run the function when the calculate button is pressed ( in this case, I was testing to see if it would display the alert if I check no radio buttons) but instead the page returns "Not found" message.
Now, I'm totally new at this so it's gone over my head as to what is wrong.
Bonus question: Could I have a hint as to how I make my function look at which buttons are selected and make a calculation from that? Example: If I wanted to selected radio button 1 (having a value of 10) and 3 (having a value of 4) the function would add them together to make 14, and so on for whichever choices you select.
function calculation() {
var cost = 0; //Base cost of flight (one way Economy)
var radioButton; // A radio button
var selection = 0; // The selected radio button, 1 to 6 going down.
for (var i = 1; i <= 6; i++) { // Get the number of the selection (1 to 6)
radioButton = document.getElementById("destination" + i);
if (radioButton.checked == true) {
selection = i;
}
// Give Base cost of flight
if (selection == 1) {
cost = 229
} else if (selection == 2) {
cost = 259
} else if (selection == 3) {
cost = 199
} else if (selection == 4) {
cost = 179
} else if (selection == 5) {
cost = 179
} else if (selection == 6) {
cost = 239
}
// Check if a flight was not selected and prompt
else if (selection == 0) {
alert("Please select a flight.");
}
seating = 0;
for (var x = 1; x <= 3; x++) {
radioButton = document.getElementById("seating" + x);
if (radioButton.checked == true) {
seating = radioButton.id;
}
}
}
}
<h1> Hawkins Airlines Fare Calculator</h1>
<p> Complete the form below to calculate the cost of your flight.</p>
<form>
<p>Route:</p>
<input type="radio" id="destination1"> Hawkins - Riverdale<br>
<input type="radio" id="destination2"> Hawkins - Haddonfield<br>
<input type="radio" id="destination3"> Hawkins - Rockwell<br>
<input type="radio" id="destination4"> Hawkins - Eagleton<br>
<input type="radio" id="destination5"> Hawkins - Pawnee<br>
<input type="radio" id="destination6"> Hawkins - Twin Peaks<br>
<br>
<input type="checkbox" name="appliances" id="return">
<label>Click here if you will be purchasing a return fare </label><br>
<p>Seating class:</p>
<input type="radio" id="seating1"> First seating<br>
<input type="radio" id="seating2"> Business seating<br>
<input type="radio" id="seating3"> Economy seating<br>
<br>
<button onclick="calculation()"> Calculate </button>
<input type="reset" value="Restore Defults">
</form>
I just fixed the javascript code. You should not use class as a variable and there was a missing {} in your first loop
<!DOCTYPE html>
<html>
<head>
</head>
<script>
function calculation() {
var cost = 0; //Base cost of flight (one way Economy)
var radioButton; // A radio button
var selection = 0; // The selected radio button, 1 to 6 going down.
for (var i = 1; i <= 6; i++) {// Get the number of the selection (1 to 6)
radioButton = document.getElementById("destination" + i);
if (radioButton.checked == true) {
selection = i;
}
}
if (selection == 1) {
cost = 229
} else if (selection == 2) {
cost = 259
} else if (selection == 3) {
cost = 199
} else if (selection == 4) {
cost = 179
} else if (selection == 5) {
cost = 179
} else if (selection == 6) {
cost = 239
} else if (selection == 0) {
alert("Please select a flight.");
return false;
}
var seating = 0;
for (var x = 1; x <= 3; x++) {
radioButton = document.getElementById("seating" + x);
if (radioButton.checked == true) {
seating = x;
}
}
var totalcost = 0;
if(seating == 0){
alert("Please select a seat.");
return false;
} else if(seating == 1){
totalcost = cost + (cost * 2);
} else if(seating == 2){
totalcost = cost + (cost * 1.5);
} else if(seating == 3){
totalcost = cost;
}
if(document.getElementById("return").checked){
totalcost = totalcost*2;
}
totalcost = totalcost + cost;
alert("Total cost: "+totalcost);
}
</script>
<body>
<h1> Hawkins Airlines Fare Calculator</h1>
<p> Complete the form below to calculate the cost of your flight.</p>
<form onsubmit="return false;">
<p>Route:</p>
<input type="radio" name="destination" id="destination1"> Hawkins - Riverdale<br>
<input type="radio" name="destination" id="destination2"> Hawkins - Haddonfield<br>
<input type="radio" name="destination" id="destination3"> Hawkins - Rockwell<br>
<input type="radio" name="destination" id="destination4"> Hawkins - Eagleton<br>
<input type="radio" name="destination" id="destination5"> Hawkins - Pawnee<br>
<input type="radio" name="destination" id="destination6"> Hawkins - Twin Peaks<br>
<br>
<input type="checkbox" name="appliances" id="return">
<label>Click here if you will be purchasing a return fare </label><br>
<p>Seating class:</p>
<input type="radio" name="seating" id="seating1"> First seating<br>
<input type="radio" name="seating" id="seating2"> Business seating<br>
<input type="radio" name="seating" id="seating3"> Economy seating<br>
<br>
<button onclick="calculation()"> Calculate </button>
<input type="reset" value="Restore Defults">
</form>
</body>
</html>
I'm trying to write a condition where:
if A is true and B is not, then it displays error_message_1
if B is true and A is not, it displays error_message_2
if both A and B are NOT true, displays error_message_3
First I tried writing all conditions in the same if...else if statement but it was very confusing so I tried putting them in different if statements and the code for that is below. the problem with this is that the third condition statement is always overridden by the first condition.
Code using html and javascript:
function calculatePrice() {
var tourType;
var payDate;
var returnTrip;
var extra = 0;
var tourCost = 0;
var discount = 0;
for (var i = 1; i <= 3; i++) {
tourType = document.getElementById("ans" + i);
if (tourType.checked == true) {
tourCost += parseFloat(tourType.value);
}
}
if (tourCost == 0 && discount !== 0) {
alert("Please select a Tour type");
return;
}
for (var a = 1; a <= 3; a++) {
payDate = document.getElementById("date" + a);
if (payDate.checked == true) {
discount += parseFloat(payDate.value);
}
}
if (discount == 0 && tourType !== 0) {
alert("Please select a Payment date.");
return;
}
for (var u = 1; u <= 1; u++) {
returnTrip = document.getElementById("return" + u);
if (returnTrip.checked == true) {
extra += parseFloat(returnTrip.value);
}
}
tourCost = tourCost - discount * tourCost + extra
tourCost = parseInt(tourCost)
if (tourCost == 0 && discount == 0) {
alert("Please select a Tour Type and Payment Date.");
return;
} else {
alert("The approximate cost of the holiday is $" + tourCost);
return;
}
}
<h1>Calculator</h1>
<p>Complete the form</p>
<form name="packages">
<p>
Tour type:<br>
<input type="radio" name="tour" id="ans1" value="3900"><label for="ans1">5-day Escape Tour</label><br>
<input type="radio" name="tour" id="ans2" value="5100"><label for="ans2">7-day Splendour Tour</label><br>
<input type="radio" name="tour" id="ans3" value="6600"><label for="ans3">10-day Best Tour</label>
</p>
<p>
Payment date:<br>
<input type="radio" name="dates" id="date1" value="0.1"><label for="date1">Before 1st November 2016</label><br>
<input type="radio" name="dates" id="date2" value="0.07"><label for="date2">Between 1st November and 31st December 2016</label><br>
<input type="radio" name="dates" id="date3" value="0.05"><label for="date3">After 31st December 2016</label>
</p>
<p>
<label for="return1">Click here if you want to include a return airfare from Australia:</label><input type="checkbox" name="return" id="return1" value="900">
</p>
<p>
<input type="submit" value="Calculate" onclick="calculatePrice();"><input type="reset" value="Reset">
</p>
</form>
Basically what I tried to do at first was to see whether any radio buttons were selected and base my if conditions on those. i tried using if (button.selected) but since each radio button has a different id, it was too long and I didn't know how to group them into one variable which I can use.
if A is true and B is not, then it displays error_message_1
if B is true and A is not, it displays error_message_2
if both A and B are NOT true, displays error_message_3
Is best written with the last condition first:
if (!A && !B) { // both are false
display(error_message_3);
} else if (!A) { // if A is false here, B must be true
display(error_message_2);
} else if (!B) { // if B is false here, A must be true
display(error_message_1);
} else { // both are true
display(no_error);
}
The conditions that you asked are :
if A is true and B is not, then it displays error_message_1
if B is true and A is not, it displays error_message_2
if both A and B are NOT true, displays error_message_3
To check if something is true you need to check if it equals to one, not zero.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Travel Agency</title>
<script type="text/javascript">
function calculatePrice() {
var tourType;
var payDate;
var returnTrip;
var extra = 0;
var tourCost = 0;
var discount = 0;
for (var i = 1; i <= 3; i++) {
tourType = document.getElementById("ans" + i);
if (tourType.checked == true) {
tourCost += parseFloat(tourType.value);
}
}
if (tourCost == 1 && discount !== 1) {
alert("Please select a Tour type");
return;
}
for (var a = 1; a <= 3; a++) {
payDate = document.getElementById("date" + a);
if (payDate.checked == true) {
discount += parseFloat(payDate.value);
}
}
if (discount == 1 && tourType !== 1) {
alert("Please select a Payment date.");
return;
}
for (var u = 1; u <= 1; u++) {
returnTrip = document.getElementById("return" + u);
if (returnTrip.checked == true) {
extra += parseFloat(returnTrip.value);
}
}
tourCost = tourCost - discount * tourCost + extra
tourCost = parseInt(tourCost)
if (tourCost !== 1 && discount !== 1) {
alert("Please select a Tour Type and Payment Date.");
return; }
else {
alert("The approximate cost of the holiday is $" + tourCost);
return; }
}
</script>
</head>
<body>
<h1>Calculator</h1>
<p>Complete the form</p>
<form name="packages">
<p>
Tour type:
<br>
<input type="radio" name="tour" id="ans1" value="3900"><label for="ans1">5-day Escape Tour</label>
<br>
<input type="radio" name="tour" id="ans2" value="5100"><label for="ans2">7-day Splendour Tour</label>
<br>
<input type="radio" name="tour" id="ans3" value="6600"><label for="ans3">10-day Best Tour</label>
</p>
<p>
Payment date:
<br>
<input type="radio" name="dates" id="date1" value="0.1"><label for="date1">Before 1st November 2016</label>
<br>
<input type="radio" name="dates" id="date2" value="0.07"><label for="date2">Between 1st November and 31st December 2016</label>
<br>
<input type="radio" name="dates" id="date3" value="0.05"><label for="date3">After 31st December 2016</label>
</p>
<p>
<label for="return1">Click here if you want to include a return airfare from Australia:</label><input type="checkbox" name="return" id="return1" value="900">
</p>
<p>
<input type="submit" value="Calculate" onclick="calculatePrice();"><input type="reset" value="Reset">
</p>
</form>
</body>
</html>
EDIT:
Hey guys, basically what i tried to do at first was to see whether any radio buttons were selected and based my if conditions on those. i tried using if (button.selected) but since each radio button has a different id, it was too long and i didn't know how to group them into one variable which i can use.
For some reason only the score0 wants to increment. Although the two for-loops seem identical (really sorry if I'm wrong). So the totScore just gets the value from the score0 variable. But ofcourse I want totScore to get value form both variables so to get the total score of the quiz.
Also, why does it add 4 to the score0 variable when I wrote score0 += 1;, that doesn't make any sence to me.
If you change my code alot please don't use any JQuery.
Thanks!
<!DOCTYPE html>
<html>
<body>
<form id='quizForm'>
<ul>
<li>
<h3>How many letters are there in 'FB'?</h3>
<input type="radio" name="question0" value="A" />2<br>
<input type="radio" name="question0" value="B" />1<br>
<input type="radio" name="question0" value="C" />3<br>
<input type="radio" name="question0" value="D" />4<br>
</li>
</ul>
<ul>
<li>
<h3>How many letters are there in 'IBM'?</h3>
<input type="radio" name="question1" value="A" />2<br>
<input type="radio" name="question1" value="B" />1<br>
<input type="radio" name="question1" value="C" />3<br>
<input type="radio" name="question1" value="D" />4<br>
</li>
</ul>
</form>
<button onclick="showScore()">Show results
</button>
<script>
//Score and answer variables
var score1 = 0;
var score0 = 0;
var totScore = 0;
var answers = ["A","C"]
//function to calculate the score.
function getScore() {
// some arrays and stuff
userInput1 = new Array(10);
userInput0 = new Array(10);
var question0s = document.getElementsByName("question0");
//for loop to see which radio was checked
for (var i = 0; i < question0s.length; i++) {
if (question0s[i].checked) {
userInput0[0] = question0s[i].value;
}
if (userInput0[0] == answers[0]) {
// Only god knows why the hell I have to divide 4
score0 += 1 / 4;
}
else if (userInput0[0] != answers [0]){
//so that user can't just switch back and fourth from inputs to get higher score.
score0 -= 1 ;
}
}
//if user has changed her answer multiple times she will get an answer with a negative value. I don't want that, so if score is less than 0 it turns to 0.
if (score0 < 0){
score0 = score0 * 0;
}
var question1s = document.getElementsByName("question1");
//for loop to see which radio was checked
for (var y = 0; y < question1s.length; y++) {
if (question1s[y].checked) {
userInput1[0] = question1[y].value;
}
if (userInput1[0] == answers[0]) {
score1 += 1;
}
else if (userInput1[0] != answers [0]){
//so that user can't just switch back and fourth from inputs to get higher score.
score1 -= 1 ;
}
}
if (score1 < 0){
//if user has changed her answer multiple times she will get an answer with a negative value. I don't want that, so if score is less than 0 it turns to 0.
score1 = score1 * 0;
}
//getting score from all different questions
totScore += score1 + score0;
}
//checking for changes in the form
var quizForm = document.getElementById('quizForm');
quizForm.addEventListener("change", function(){
getScore();
});
// onclick function
function showScore (){
alert (totScore);
}
</script>
</body>
</html>
As to why you are not getting proper processing, you have an invalid variable question1 here:
userInput1[0] = question1[y].value;
Now let's fix this and do better.
First off, you have a number of global variables so let's get that under a simple namespace and call it quiz.
Get the click handler out of the markup and create a listener for that.
Now as for your logic, you are looping through the radio buttons. Now the way radio buttons work is that only one can be selected SO, let's use that to our advantage an not do the loop at all.
With the radio buttons, if one is NOT selected yet, then it will be NULL using our new selection technique so we can use that to tell if both the questions have been answered and then if that IS true, we can put scores in. Otherwise, they get no score (score is 0) until all the questions ARE answered (not NULL).
//Score and answer variables=
var quiz = {
score0: 0,
score1: 0,
totalScore: 0,
answers: ["A", "C"],
maxScore: 2,
tries: 0
};
//function to calculate the score.
function getScore() {
var answer0 = document.querySelector('input[name="question0"]:checked');
quiz.score0 = answer0 != null && quiz.answers[0] == answer0.value ? 1 : 0;
var answer1 = document.querySelector('input[name="question1"]:checked');
quiz.score1 = answer1 != null && quiz.answers[1] == answer1.value ? 1 : 0;
// if either is null, not all answered
if (answer0 != null && answer1 != null) {
// if previous tries, subtract how many
if (quiz.tries) {
quiz.totalScore = quiz.totalScore ? quiz.totalScore - quiz.tries : 0;
quiz.totalScore = quiz.totalScore < 0 ? 0 : quiz.totalScore ;//0 if negative
} else {
quiz.totalScore = quiz.score1 + quiz.score0;
}
quiz.tries++;
}
}
// onclick function
function showScore() {
alert(quiz.totalScore + " in tries: " + quiz.tries);
}
// add listeners
//checking for changes in the form
var quizForm = document.getElementById('quizForm');
quizForm.addEventListener("change", function() {
getScore();
});
var resultButton = document.getElementById('results');
resultButton.addEventListener("click", function() {
showScore();
});
Try the above out here: https://jsfiddle.net/MarkSchultheiss/qx4hLjLq/2/
You could also do more with this by putting that in the quiz something like this:
//Score and answer variables=
var quiz = {
totalScore: 0,
tries: 0,
maxScore: 2,
answered: 0,
questions: [{
question: {},
name: "question0",
score: 0,
answer: "A"
}, {
question: {},
name: "question1",
score: 0,
answer: "C"
}],
checkQuestion: function(q) {
q.score = q.question != null && q.answer == q.question.value ? 1 : 0;
},
//function to calculate the score.
getScore: function() {
this.answered = 0;
for (var i = 0; i < this.questions.length; i++) {
var sel = 'input[name="' + this.questions[i].name + '"]:checked';
this.questions[i].question = document.querySelector(sel);
this.checkQuestion(this.questions[i]);
this.answered = this.questions[i].question ? this.answered + 1 : this.answered;
}
console.dir(this);
// if either is null, not all answered
if (this.answered == this.questions.length) {
for (var i = 0; i < this.questions.length; i++) {
this.totalScore = this.totalScore + this.questions[i].score;
}
if (this.tries) {
this.totalScore = this.tries && this.totalScore ? this.totalScore - this.tries : 0;
this.totalScore = this.totalScore < 0 ? 0 : this.totalScore; //0 if negative
}
this.tries++;
}
},
// onclick function
showScore: function() {
var t = "";
if (this.answered != this.questions.length) {
t = "Not all questions ansered!"
} else {
t = this.totalScore + " in tries: " + this.tries;
}
alert(t);
}
};
// add listeners
//checking for changes in the form
var quizForm = document.getElementById('quizForm');
quizForm.addEventListener("change", function() {
quiz.getScore();
});
var resultButton = document.getElementById('results');
resultButton.addEventListener("click", function() {
quiz.showScore();
});
Second example in action: https://jsfiddle.net/MarkSchultheiss/qx4hLjLq/4/
Well if you want to simply get the result from the test, use this code:
<!DOCTYPE html>
<html>
<body>
<ul>
<li>
<h3>How many letters are there in 'FB'?</h3>
<input type="radio" name="question0"/>1<br>
<input type="radio" name="question0"/>2<br>
<input type="radio" name="question0"/>3<br>
<input type="radio" name="question0"/>4<br>
</li>
</ul>
<ul>
<li>
<h3>How many letters are there in 'IBM'?</h3>
<input type="radio" name="question1"/>1<br>
<input type="radio" name="question1"/>2<br>
<input type="radio" name="question1"/>3<br>
<input type="radio" name="question1"/>4<br>
</li>
</ul>
<button onclick="calculate()">Submit</button>
<script>
function calculate(){
var answers = [1, 2];
var score = 0;
var question0s = document.getElementsByName("question0");
var question1s = document.getElementsByName("question1");
if (question0s[answers[0]].checked == true) {
score++;
}
if (question1s[answers[1]].checked == true) {
score++;
}
alert ("You got " + score + " out of " + answers.length + ".");
}
</script>
</body>
</html>
It looks like you're calling the script every time an answer changes, and this is very inefficient. I'm only calling when all the answers have been made and the user presses submit.
And the reason why that is adding 4 times is because if you set your first answer to A, it writes it to userinput0 and doesn't get changed anymore since the answer was the only one checked, and it repeats the amount of choices there are, in which there were 4. Thus you are repeating that assignment statement 4 times so you are adding 4.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I added the alert to test if the script was working at all, once i deleted the function it did, but once I add the function the html doesn't even show the alert. I tried loading the code in a different file and calling it in the head, the body, for some reason the code won't even load much less can i get the button at the end to work.
<!DOCTYPE html>
<html>
<head>
<title> Astronomy Quiz </title>
</head>
<body>
<div>
<script>
alert("Quiz");
function quiz() {
var grade = 0;
var get = document.getElementById("quiz");
if (get.q1[1].checked) {
grade += 1;
} else if (!get.q1[0].checked) {
alert("Please answer the first question.");
return;
}
if (get.q2[0].checked) {
grade += 1;
} else if (!get.q2[1].checked) {
alert("Please answer the second question.");
return;
}
var check = 0;
var gradeCheck = 0;
if (get.q3[1].checked) {
check += 1;
gradeCheck += 1;
}
for (var i = 0; i < 4; i++) {
if (get.q3[i].checked && i != 1) {
check += 1;
gradeCheck = 0;
}
}
if (check == 0) {
alert("Please answer the third question.");
return;
}
grade += gradeCheck;
check = 0;
gradeCheck = 0;
if (get.q4[3].checked) {
check += 1;
gradeCheck += 1;
}
for (var i = 0; i < 4; i++) {
if (get.q4[i].checked && i != 3) {
check += 1;
gradeCheck = 0;
}
}
if (check == 0) {
alert("Please answer the fourth question.");
return;
}
grade += gradeCheck;
if (get.q5.value.match(/^galaxy$/i)) {
grade += 1;
}
if (get.q5.value == "") {
alert("PLease answer the fifth question.");
return;
}
if (get.q6.value.match(/^age$/i)) {
grade += 1;
}
if (get.q6.value == "") {
alert("PLease answer the sixth question.");
return;
}
alert("Your grade is " + grade + " / 6.");
}
</script>
<center>
<h1> Astronomy Quiz </h1>
</center>
<h3> True / False </h3>
<form id = "quiz">
<label><b>1)</b> According to Kepler the orbit of the earth is a circle with
the sun at the center.
<input type = "radio" name = "q1" value = "True" />
True
<input type = "radio" name = "q1" value = "False" />
False</label>
<br>
<br>
<label><b>2)</b> Ancient astronomers did consider the heliocentric model of
the solar system but rejected it because they could not detect parallax.
<input type = "radio" name = "q2" value = "True" />
True
<input type = "radio" name = "q2" value = "True" />
False</label>
<br>
<h3> Multiple Choice </h3>
<b>3)</b> The total amount of energy that a star emits is directly related
to its
<br>
<input type = "checkbox" name = "q3" value = "a" />
a) surface gravity and magnetic field
<br>
<input type = "checkbox" name = "q3" value = "b" />
b) radius and temperature
<br>
<input type = "checkbox" name = "q3" value = "c" />
c) pressure and volume
<br>
<input type = "checkbox" name = "q3" value = "d" />
d) location and velocity
<br>
<br>
<b>4)</b> Stars that live the longest have
<br>
<input type = "checkbox" name = "q4" value = "a" />
a) high mass
<br>
<input type = "checkbox" name = "q4" value = "b" />
b) high temperature
<br>
<input type = "checkbox" name = "q4" value = "c" />
c) lots of hydrogen
<br>
<input type = "checkbox" name = "q4" value = "d" />
d) small mass
<br>
<h3> Fill in the Blank </h3>
<label><b>5)</b> A collection of a hundred billion stars, gas, and dust is
called a
<input type = "text" name = "q5" value = "" size = "15" />
.</label>
<br>
<br>
<label><b>6)</b> The inverse of the Hubble's constant is a measure of the
<input type = "text" name = "q6" value = "" size = "15" />
of the universe.</label>
<br>
<br />
<input type = "button" value = "Grade" onclick = "quiz()" />
<input type = "reset" name = "Clear" value = "Clear" />
</form>
</div>
</body>
</html>
Try this out:- http://jsfiddle.net/adiioo7/fDDCW/
JS:-
alert("Quiz");
function quiz() {
var grade = 0;
var get = document.getElementById("quiz");
if (get.q1[1].checked) {
grade += 1;
} else if (!get.q1[0].checked) {
alert("Please answer the first question.");
return;
}
if (get.q2[0].checked) {
grade += 1;
} else if (!get.q2[1].checked) {
alert("Please answer the second question.");
return;
}
var check = 0;
var gradeCheck = 0;
if (get.q3[1].checked) {
check += 1;
gradeCheck += 1;
}
for (var i = 0; i < 4; i++) {
if (get.q3[i].checked && i != 1) {
check += 1;
gradeCheck = 0;
}
}
if (check == 0) {
alert("Please answer the third question.");
return;
}
grade += gradeCheck;
check = 0;
gradeCheck = 0;
if (get.q4[3].checked) {
check += 1;
gradeCheck += 1;
}
for (var i = 0; i < 4; i++) {
if (get.q4[i].checked && i != 3) {
check += 1;
gradeCheck = 0;
}
}
if (check == 0) {
alert("Please answer the fourth question.");
return;
}
grade += gradeCheck;
if (get.q5.value.match(/^galaxy$/i)) {
grade += 1;
}
if (get.q5.value == "") {
alert("PLease answer the fifth question.");
return;
}
if (get.q6.value.match(/^age$/i)) {
grade += 1;
}
if (get.q6.value == "") {
alert("PLease answer the sixth question.");
return;
}
alert("Your grade is " + grade + " / 6.");
}
on line 88:
if(get.q6.value.match(/^age$/i))
you missed ) in your javascript...
You have missed a ) here:
if(get.q6.value.match(/^age$/i)
Change this to:
if(get.q6.value.match(/^age$/i))
if (get.q6.value.match(/^age$/i) {
This like is missing a closing )
Try this:
if (get.q6.value.match(/^age$/i)) {
To find what's wrong with your JavaScript code use try-catch as follows-
<script>
try
{
/*some JS code*/
}
catch(foo)//Use any variable in place of foo
{
alert(foo);
}
</script>
This will definitely not correct the error but may help you much to find what the error is. Though this is not an answer but you may follow this approach globally anywhere anytime.
I've looked through many posts to no avail. I have the following in a simple form where one of the products changes based on the number of checkboxes checked. It works in every browser except IE. What am I doing wrong?
<body>
<script type="text/javascript">
function check(){
"use strict";
var count = 0, x=0, checkboxes=document.signup.getElementsByClassName("styled");
for(;x<checkboxes.length; x++){
if(checkboxes[x].checked){
count++;
}
}
if(count<3) {
document.getElementById("variable").value = "1";
}
else if (count == 3){
document.getElementById("variable").value = "74";
}
else if (count == 4){
document.getElementById("variable").value = "75";
}
else if (count == 5){
document.getElementById("variable").value = "76";
}
}
</script>
<form name="signup" id="signup" method="post" action="/subscribers/signup.php">
<input type="checkbox" id="variable" name="product_id[]" value="" class="styled"></input>product 1 - variable</div>
<input type="checkbox" id="same" name="product_id[]" value="3" class="styled"></input>product 2
<input type="checkbox" id="same2" name="product_id[]" value="2" class="styled"></input>product 3
<input type="checkbox" id="same3" name="product_id[]" value="4" class="styled"></input><div class="check-title">product 4
<input type="checkbox" id="same4" name="product_id[]" value="44" class="styled"></input><div class="check-title">product 5
Continue</td></tr>
</form>
</body>
All versions of IE prior to IE9 do not support getElementsByClassName(). You will need to use some sort of substitute.
Instead of this piece of your code:
checkboxes = document.signup.getElementsByClassName("styled");
I would suggest using this:
checkboxes = document.getElementById("signup").getElementsByTagName("input")
getElementsByTagName() is widely support in all versions of IE. This will obviously get all input tags, but only the checkboxes will have checked set so you should be OK.
If you need to filter by class, then you could do the whole thing this way:
function check() {
"use strict";
// initialize checkbox count to 0
var count = 0, item;
// get all input tags in the form
var inputs = document.getElementById("signup").getElementsByTagName("input");
// loop through all input tags in the form
for (var i = 0; i < inputs.length; i++) {
// get this one into the local variable item
item = inputs[i];
// if this input tag has the right classname and is checked, increment the count
if ((item.className.indexOf("styled") != -1) && item.checked) {
count++;
}
}
// get object for result
var obj = document.getElementById("variable");
// check count and set result based on the count
if(count < 3) {
obj.value = "1";
} else if (count == 3) {
obj.value = "74";
} else if (count == 4) {
obj.value = "75";
} else if (count == 5) {
obj.value = "76";
}
}
IE doesnt have method getElementsByClassName... you can try to define it:
if(document.getElementsByClassName == undefined) {
document.getElementsByClassName = function(cl) {
var retnode = [];
var myclass = new RegExp('\\b'+cl+'\\b');
var elem = this.getElementsByTagName('*');
for (var i = 0; i < elem.length; i++) {
var classes = elem[i].className;
if (myclass.test(classes)) {
retnode.push(elem[i]);
}
}
return retnode;
}
};