I want to build a simple and easy Javascript-based quiz application(remember simple and easy code not with advanced Javascript) I tried my best but I am stuck at this point everything is working fine except the result. I want to get results in a html tag using Javascript. Here is my code:
// Javascript (important I need a solution in this code)
function check(){
// question no1
var score = 0;
var q1WriteAnswer = document.getElementById('q1_o3');
var q1option1 = document.getElementById('q1_o1');
var q1option2 = document.getElementById('q1_o2');
var q1option4 = document.getElementById('q1_o4');
if (q1WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// question no2
var score = 0;
var q2WriteAnswer = document.getElementById('q2_o1');
var q2option1 = document.getElementById('q2_o2');
var q2option2 = document.getElementById('q2_o3');
var q2option4 = document.getElementById('q2_o4');
if (q2WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// Question no3
var score = 0;
var q3WriteAnswer = document.getElementById('q3_o2');
var q3option1 = document.getElementById('q3_o1');
var q3option2 = document.getElementById('q3_o3');
var q3option4 = document.getElementById('q3_o4');
if (q3WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// Question no4
var score = 0;
var q4WriteAnswer = document.getElementById('q4_o4');
var q4option1 = document.getElementById('q4_o1');
var q4option2 = document.getElementById('q4_o2');
var q4option4 = document.getElementById('q4_o3');
if (q4WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// Question no5
var score = 0;
var q5WriteAnswer = document.getElementById('q5_o1');
var q5option1 = document.getElementById('q5_o2');
var q5option2 = document.getElementById('q5_o3');
var q5option4 = document.getElementById('q5_o4');
if (q5WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// Question no6
var score = 0;
var q6WriteAnswer = document.getElementById('q6_o1');
var q6option1 = document.getElementById('q6_o2');
var q6option2 = document.getElementById('q6_o3');
var q6option4 = document.getElementById('q6_o4');
if (q6WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// Questiton No7
var score = 0;
var q7WriteAnswer = document.getElementById('q7_o1');
var q7option1 = document.getElementById('q7_o2');
var q7option2 = document.getElementById('q7_o3');
var q7option4 = document.getElementById('q7_o4');
if (q7WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// Question no 8
var score = 0;
var q8WriteAnswer = document.getElementById('q8_o1');
var q8option1 = document.getElementById('q8_o2');
var q8option2 = document.getElementById('q8_o3');
var q8option4 = document.getElementById('q8_o4');
if (q8WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// Question No9
var score = 0;
var q9WriteAnswer = document.getElementById('q9_o3');
var q9option1 = document.getElementById('q9_o1');
var q9option2 = document.getElementById('q9_o2');
var q9option4 = document.getElementById('q9_o4');
if (q9WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// Question No10
var score = 0;
var q10WriteAnswer = document.getElementById('q10_o1');
var q10option1 = document.getElementById('q10_o2');
var q10option2 = document.getElementById('q10_o3');
var q10option4 = document.getElementById('q10_o4');
if (q10WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
var ab = document.createElement("h3");
ab.innerText = score;
document.body.appendChild(ab);
}
/* *{
padding: 0px;
margin: 0px;
} */
body{
color: white;
background-color: #222;
background-image: url(images/bg.jpg);
background-repeat: no-repeat;
background-size: cover;
background-position: center;
}
fieldset{
border-radius: 15px;
text-align: center;
}
h3{
background-color: cornsilk;
color: blue;
width: 10vw;
height: 5vh;
text-align: center;
position: relative;
left: 45%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Quiz Application</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Quiz Application</h1>
<div>
<fieldset>
<p>Who is the founder of Pakistan?</p>
<input type="radio" name="founder" id="q1_o1">Allama Iqbal</radio>
<input type="radio" name="founder" id="q1_o2">Manzoor Kapri</radio>
<input type="radio" name="founder" id="q1_o3">Quaid-e-Azam</radio>
<input type="radio" name="founder" id="q1_o4">Liaquat Ali Jinah</radio>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Who is national poet of Pakistan?</p>
<input type="radio" name="national_poet" id="q2_o1">Allama Iqbal</radio>
<input type="radio" name="national_poet" id="q2_o2">Manzoor Kapri</radio>
<input type="radio" name="national_poet" id="q2_o3">Quaid-e-Azam</radio>
<input type="radio" name="national_poet" id="q2_o4">Liaquat Ali Jinah</radio>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Who is the writer of national anthem of Pakistan?</p>
<input type="radio" name="anthem_poet" id="q3_o1">Allama Iqbal</radio>
<input type="radio" name="anthem_poet" id="q3_o2">Hafiz Jalindheri</radio>
<input type="radio" name="anthem_poet" id="q3_o3">Quaid-e-Azam</radio>
<input type="radio" name="anthem_poet" id="q3_o4">Liaquat Ali Jinah</radio>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>what is the national animal of Pakistan?</p>
<input type="radio" name="national_animal" id="q4_o1">Peacock</radio>
<input type="radio" name="national_animal" id="q4_o2">Dog</radio>
<input type="radio" name="national_animal" id="q4_o3">Lion</radio>
<input type="radio" name="national_animal" id="q4_o4">Markhor</radio>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Who is the Prime Minister of Pakistan?</p>
<input type="radio" name="pm" id="q5_o1">Imran Khan</radio>
<input type="radio" name="pm" id="q5_o2">Manzoor Kapri</radio>
<input type="radio" name="pm" id="q5_o3">Quaid-e-Azam</radio>
<input type="radio" name="pm" id="q5_o4">Liaquat Ali Jinah</radio>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>what is the area of pakistan in square km?</p>
<input type="radio" name="pk_sq_km" id="q6_o1">1,96,096 sq km</radio>
<input type="radio" name="pk_sq_km" id="q6_o1">5,05,095 sq km</radio>
<input type="radio" name="pk_sq_km" id="q6_o1">7,96,096 sq km</radio>
<input type="radio" name="pk_sq_km" id="q6_o1">2,96,096 sq km</radio>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Who is the first prime minister of Pakistan?</p>
<input type="radio" name="first_PM" id="q7_o1">Liaquat Ali</radio>
<input type="radio" name="first_PM" id="q7_o2">Zulfiqar Ali Bhutto</radio>
<input type="radio" name="first_PM" id="q7_o3">Quaid-e-Azam</radio>
<input type="radio" name="first_PM" id="q7_o4">Manzoor Kapri</radio>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Which was the first capital of Pakistan?</p>
<input type="radio" name="first_Capital" id="q8_o1">Karachi</radio>
<input type="radio" name="first_Capital" id="q8_o2">Islamabad</radio>
<input type="radio" name="first_Capital" id="q8_o3">Hydrabad</radio>
<input type="radio" name="first_Capital" id="q8_o4">Quetta</radio>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Who is the first woman prime minister of Pakistan?</p>
<input type="radio" name="first_womanPM" id="q9_o1">Shoukat Khanam</radio>
<input type="radio" name="first_womanPM" id="q9_o2">Shamshad Akhtar</radio>
<input type="radio" name="first_womanPM" id="q9_o3">Benazir Bhutto</radio>
<input type="radio" name="first_womanPM" id="q9_o4">Liaquat Ali Jinah</radio>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>which is the current capital of Pakistan?</p>
<input type="radio" name="founder" id="">Islamabad</radio>
<input type="radio" name="founder" id="">Karachi</radio>
<input type="radio" name="founder" id="">Hydrabad</radio>
<input type="radio" name="founder" id="">Lahore</radio>
</fieldset>
</div><br>
<br>
<br>
<button onclick="check()">Results</button>
<script src="app.js"></script>
</body>
</html>
It can be done easier using the querySelector an example:
// Javascript (important I need a solution in this code)
function checkQuestion(questionName, answerID) {
if(questionName == null || answerID == null) return;
const answer = document.getElementById(answerID);
const question = document.querySelector(`input[name="${questionName}"]:checked`);
if(answer == null || question == null) return;
return answer.id === question.id;
}
function updateScore(name, score, isCorrect) {
if(isCorrect == null) return score;
if(isCorrect) {
document.querySelectorAll(`input[name="${name}"]:not(:checked)`).forEach(input => input.disabled = true);
return score + 1;
}
else alert("wrong answer");
return score;
}
function check() {
let score = 0;
// question no1
const nameQ1 = 'founder'
const validQ1 = checkQuestion(nameQ1, 'q1_o3');
score = updateScore(nameQ1, score, validQ1);
// question no2
const nameQ2 = 'national_poet';
const validQ2 = checkQuestion(nameQ2, 'q2_o1');
score = updateScore(nameQ2, score, validQ2);
// question no3
const nameQ3 = 'anthem_poet'
const validQ3 = checkQuestion(nameQ3, 'q3_o2');
score = updateScore(nameQ3, score, validQ3);
// question no4
const nameQ4 = 'national_animal'
const validQ4 = checkQuestion(nameQ4, 'q4_o4');
score = updateScore(nameQ4, score, validQ4);
// question no5
const nameQ5 = 'pm';
const validQ5 = checkQuestion(nameQ5, 'q5_o1');
score = updateScore(nameQ5, score, validQ5);
// question no6
const nameQ6 = 'pk_sq_km'
const validQ6 = checkQuestion(nameQ6, 'q6_o1');
score = updateScore(nameQ6, score, validQ6);
// question no7
const nameQ7 = 'first_PM';
const validQ7 = checkQuestion(nameQ7, 'q7_o1');
score = updateScore(nameQ7, score, validQ7);
// question no8
const nameQ8 = 'first_Capital';
const validQ8 = checkQuestion(nameQ8, 'q8_o1');
score = updateScore(nameQ8, score, validQ8);
// question no9
const nameQ9 = 'first_womanPM';
const validQ9 = checkQuestion(nameQ9, 'q9_o3');
score = updateScore(nameQ9, score, validQ9);
// question no9
const nameQ10 = 'founder2';
const validQ10 = checkQuestion(nameQ10, 'q10_o1');
score = updateScore(nameQ10, score, validQ10);
//display result
const ab = document.querySelector('.ab') || ((e) => {
e.classList.add('ab');
document.body.appendChild(e)
return e;
})(document.createElement("h3"));
ab.innerText = score;
}
/* *{
padding: 0px;
margin: 0px;
} */
body{
margin: 1em;
color: white;
background-color: #222;
background-image: url(images/bg.jpg);
background-repeat: no-repeat;
background-size: cover;
background-position: center;
}
fieldset{
border-radius: 15px;
text-align: center;
}
h3{
background-color: cornsilk;
color: blue;
width: 10vw;
height: 5vh;
text-align: center;
position: relative;
left: 45%;
}
input[type=radio]:disabled ~ label {
color: gray;
}
<h1>Quiz Application</h1>
<div>
<fieldset>
<p>Who is the founder of Pakistan?</p>
<input type="radio" name="founder" id="q1_o1"><label>Allama Iqbal</label>
<input type="radio" name="founder" id="q1_o2"><label>Manzoor Kapri</label>
<input type="radio" name="founder" id="q1_o3"><label>Quaid-e-Azam</label>
<input type="radio" name="founder" id="q1_o4"><label>Liaquat Ali Jinah</label>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Who is national poet of Pakistan?</p>
<input type="radio" name="national_poet" id="q2_o1"><label>Allama Iqbal</label>
<input type="radio" name="national_poet" id="q2_o2"><label>Manzoor Kapri</label>
<input type="radio" name="national_poet" id="q2_o3"><label>Quaid-e-Azam</label>
<input type="radio" name="national_poet" id="q2_o4"><label>Liaquat Ali Jinah</label>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Who is the writer of national anthem of Pakistan?</p>
<input type="radio" name="anthem_poet" id="q3_o1"><label>Allama Iqbal</label>
<input type="radio" name="anthem_poet" id="q3_o2"><label>Hafiz Jalindheri</label>
<input type="radio" name="anthem_poet" id="q3_o3"><label>Quaid-e-Azam</label>
<input type="radio" name="anthem_poet" id="q3_o4"><label>Liaquat Ali Jinah</label>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>what is the national animal of Pakistan?</p>
<input type="radio" name="national_animal" id="q4_o1"><label>Peacock</label>
<input type="radio" name="national_animal" id="q4_o2"><label>Dog</label>
<input type="radio" name="national_animal" id="<label>q4_o3"><label>Lion</label>
<input type="radio" name="national_animal" id="q4_o4"><label>Markhor</label>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Who is the Prime Minister of Pakistan?</p>
<input type="radio" name="pm" id="q5_o1"><label>Imran Khan</label>
<input type="radio" name="pm" id="q5_o2"><label>Manzoor Kapri</label>
<input type="radio" name="pm" id="q5_o3"><label>Quaid-e-Azam</label>
<input type="radio" name="pm" id="q5_o4"><label>Liaquat Ali Jinah</label>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>what is the area of pakistan in square km?</p>
<input type="radio" name="pk_sq_km" id="q6_o1"><label>1,96,096 sq km</label>
<input type="radio" name="pk_sq_km" id="q6_o1"><label>5,05,095 sq km</label>
<input type="radio" name="pk_sq_km" id="q6_o1"><label>7,96,096 sq km</label>
<input type="radio" name="pk_sq_km" id="q6_o1"><label>2,96,096 sq km</label>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Who is the first prime minister of Pakistan?</p>
<input type="radio" name="first_PM" id="q7_o1"><label>Liaquat Ali</label>
<input type="radio" name="first_PM" id="q7_o2"><label>Zulfiqar Ali Bhutto</label>
<input type="radio" name="first_PM" id="q7_o3"><label>Quaid-e-Azam</label>
<input type="radio" name="first_PM" id="q7_o4"><label>Manzoor Kapri</label>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Which was the first capital of Pakistan?</p>
<input type="radio" name="first_Capital" id="q8_o1"><label>Karachi</label>
<input type="radio" name="first_Capital" id="q8_o2"><label>Islamabad</label>
<input type="radio" name="first_Capital" id="q8_o3"><label>Hydrabad</label>
<input type="radio" name="first_Capital" id="q8_o4"><label>Quetta</label>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Who is the first woman prime minister of Pakistan?</p>
<input type="radio" name="first_womanPM" id="q9_o1"><label>Shoukat Khanam</label>
<input type="radio" name="first_womanPM" id="q9_o2"><label>Shamshad Akhtar</label>
<input type="radio" name="first_womanPM" id="q9_o3"><label>Benazir Bhutto</label>
<input type="radio" name="first_womanPM" id="q9_o4"><label>Liaquat Ali Jinah</label>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>which is the current capital of Pakistan?</p>
<input type="radio" name="founder2" id=""><label>Islamabad</label>
<input type="radio" name="founder2" id=""><label>Karachi</label>
<input type="radio" name="founder2" id=""><label>Hydrabad</label>
<input type="radio" name="founder2" id=""><label>Lahore</label>
</fieldset>
</div><br>
<br>
<br>
<button onclick="check()">Results</button>
The radio input elements were incorrect. You would want to add a label element beneath each input type="radio" and remove the closing radio tag.
You can then simplify your javascript by checking if only the correct answer is selected. I provided a code example with the script at the bottom.
By getting only the correct answer input elements, you can store them in an array and loop over the array to see if the correct answer is checked.
I provided an example to show a better way to get what you are looking for.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Quiz Application</h1>
<h2>Score: <span id="score">0</span></h2>
<div>
<fieldset>Who is the founder of Pakistan? <br>
<input type="radio" name="founder" id="q1_o1" value="Allama Iqbal">
<label for="founder">Allama Iqbal</label>
<input type="radio" name="founder" id="q1_o2" value="Manzoor Kapri">
<label for="founder">Manzoor Kapri</label>
<input type="radio" name="founder" id="q1_o3" value="Quaid-e-Azam">
<label for="founder">Liaquat Ali Jinah</label>
<input type="radio" name="founder" id="q1_o4" value="Liaquat Ali Jinah">
<label for="founder">Liaquat Ali Jinah</label>
</fieldset>
<fieldset>Who is the national poet of Pakistan? <br>
<input type="radio" name="national_poet" id="q2_o1" value="Allama Iqbal">
<label for="national_poet">Allama Iqbal</label>
<input type="radio" name="national_poet" id="q2_o2" value="Manzoor Kapri">
<label for="national_poet">Manzoor Kapri</label>
<input type="radio" name="national_poet" id="q2_o3" value="Quaid-e-Azam">
<label for="national_poet">Liaquat Ali Jinah</label>
<input type="radio" name="national_poet" id="q2_o4" value="Liaquat Ali Jinah">
<label for="national_poet">Liaquat Ali Jinah</label>
</fieldset>
</div>
<button onClick="check()">Check Answer</button>
<script>
function check(){
// question no1
var score = 0;
var wrong_count = 0;
var scoreNode = document.getElementById('score');
const answer1 = document.getElementById('q1_o3');
const answer2 = document.getElementById('q2_o1');
const answers = [answer1, answer2];
answers.forEach(answer => {
if (answer.checked) {
score++
} else {
wrong_count++
}
})
scoreNode.innerHTML = score;
if (wrong_count > 0) {
alert(`You answered ${wrong_count} question(s) incorrectly.`);
}
}
</script>
</body>
</html>
you have a few mistakes:
you keep adding a closing < /radio > that shouldn't be there
you keep resetting sum to 0
you js has 10 questions your html has 9
your append to body is incorrect
// Javascript (important I need a solution in this code)
function check(){
// question no1
var score = 0;
var q1WriteAnswer = document.getElementById('q1_o3');
var q1option1 = document.getElementById('q1_o1');
var q1option2 = document.getElementById('q1_o2');
var q1option4 = document.getElementById('q1_o4');
if (q1WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// question no2
// var score = 0;
var q2WriteAnswer = document.getElementById('q2_o1');
var q2option1 = document.getElementById('q2_o2');
var q2option2 = document.getElementById('q2_o3');
var q2option4 = document.getElementById('q2_o4');
if (q2WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// Question no3
// var score = 0;
var q3WriteAnswer = document.getElementById('q3_o2');
var q3option1 = document.getElementById('q3_o1');
var q3option2 = document.getElementById('q3_o3');
var q3option4 = document.getElementById('q3_o4');
if (q3WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// Question no4
// var score = 0;
var q4WriteAnswer = document.getElementById('q4_o4');
var q4option1 = document.getElementById('q4_o1');
var q4option2 = document.getElementById('q4_o2');
var q4option4 = document.getElementById('q4_o3');
if (q4WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// Question no5
// var score = 0;
var q5WriteAnswer = document.getElementById('q5_o1');
var q5option1 = document.getElementById('q5_o2');
var q5option2 = document.getElementById('q5_o3');
var q5option4 = document.getElementById('q5_o4');
if (q5WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// Question no6
// var score = 0;
var q6WriteAnswer = document.getElementById('q6_o1');
var q6option1 = document.getElementById('q6_o2');
var q6option2 = document.getElementById('q6_o3');
var q6option4 = document.getElementById('q6_o4');
if (q6WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// Questiton No7
// var score = 0;
var q7WriteAnswer = document.getElementById('q7_o1');
var q7option1 = document.getElementById('q7_o2');
var q7option2 = document.getElementById('q7_o3');
var q7option4 = document.getElementById('q7_o4');
if (q7WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// Question no 8
// var score = 0;
var q8WriteAnswer = document.getElementById('q8_o1');
var q8option1 = document.getElementById('q8_o2');
var q8option2 = document.getElementById('q8_o3');
var q8option4 = document.getElementById('q8_o4');
if (q8WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// Question No9
// var score = 0;
var q9WriteAnswer = document.getElementById('q9_o3');
var q9option1 = document.getElementById('q9_o1');
var q9option2 = document.getElementById('q9_o2');
var q9option4 = document.getElementById('q9_o4');
if (q9WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// Question No10
/*
var score = 0;
var q10WriteAnswer = document.getElementById('q10_o1');
var q10option1 = document.getElementById('q10_o2');
var q10option2 = document.getElementById('q10_o3');
var q10option4 = document.getElementById('q10_o4');
if (q10WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
*/
var ab = document.createElement("h3");
ab.innerText = score;
document.getElementsByTagName('body')[0].appendChild(ab);
}
/* *{
padding: 0px;
margin: 0px;
} */
body{
color: white;
background-color: #222;
background-image: url(images/bg.jpg);
background-repeat: no-repeat;
background-size: cover;
background-position: center;
}
fieldset{
border-radius: 15px;
text-align: center;
}
h3{
background-color: cornsilk;
color: blue;
width: 10vw;
height: 5vh;
text-align: center;
position: relative;
left: 45%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Quiz Application</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Quiz Application</h1>
<div>
<fieldset>
<p>Who is the founder of Pakistan?</p>
<input type="radio" name="founder" id="q1_o1">Allama Iqbal
<input type="radio" name="founder" id="q1_o2">Manzoor Kapri
<input type="radio" name="founder" id="q1_o3">Quaid-e-Azam
<input type="radio" name="founder" id="q1_o4">Liaquat Ali Jinah
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Who is national poet of Pakistan?</p>
<input type="radio" name="national_poet" id="q2_o1">Allama Iqbal
<input type="radio" name="national_poet" id="q2_o2">Manzoor Kapri
<input type="radio" name="national_poet" id="q2_o3">Quaid-e-Azam
<input type="radio" name="national_poet" id="q2_o4">Liaquat Ali Jinah
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Who is the writer of national anthem of Pakistan?</p>
<input type="radio" name="anthem_poet" id="q3_o1">Allama Iqbal
<input type="radio" name="anthem_poet" id="q3_o2">Hafiz Jalindheri
<input type="radio" name="anthem_poet" id="q3_o3">Quaid-e-Azam
<input type="radio" name="anthem_poet" id="q3_o4">Liaquat Ali Jinah
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>what is the national animal of Pakistan?</p>
<input type="radio" name="national_animal" id="q4_o1">Peacock
<input type="radio" name="national_animal" id="q4_o2">Dog
<input type="radio" name="national_animal" id="q4_o3">Lion
<input type="radio" name="national_animal" id="q4_o4">Markhor
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Who is the Prime Minister of Pakistan?</p>
<input type="radio" name="pm" id="q5_o1">Imran Khan
<input type="radio" name="pm" id="q5_o2">Manzoor Kapri
<input type="radio" name="pm" id="q5_o3">Quaid-e-Azam
<input type="radio" name="pm" id="q5_o4">Liaquat Ali Jinah
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>what is the area of pakistan in square km?</p>
<input type="radio" name="pk_sq_km" id="q6_o1">1,96,096 sq km
<input type="radio" name="pk_sq_km" id="q6_o1">5,05,095 sq km
<input type="radio" name="pk_sq_km" id="q6_o1">7,96,096 sq km
<input type="radio" name="pk_sq_km" id="q6_o1">2,96,096 sq km
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Who is the first prime minister of Pakistan?</p>
<input type="radio" name="first_PM" id="q7_o1">Liaquat Ali
<input type="radio" name="first_PM" id="q7_o2">Zulfiqar Ali Bhutto
<input type="radio" name="first_PM" id="q7_o3">Quaid-e-Azam
<input type="radio" name="first_PM" id="q7_o4">Manzoor Kapri
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Which was the first capital of Pakistan?</p>
<input type="radio" name="first_Capital" id="q8_o1">Karachi
<input type="radio" name="first_Capital" id="q8_o2">Islamabad
<input type="radio" name="first_Capital" id="q8_o3">Hydrabad
<input type="radio" name="first_Capital" id="q8_o4">Quetta
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Who is the first woman prime minister of Pakistan?</p>
<input type="radio" name="first_womanPM" id="q9_o1">Shoukat Khanam
<input type="radio" name="first_womanPM" id="q9_o2">Shamshad Akhta
<input type="radio" name="first_womanPM" id="q9_o3">Benazir Bhutto
<input type="radio" name="first_womanPM" id="q9_o4">Liaquat Ali Jinah
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>which is the current capital of Pakistan?</p>
<input type="radio" name="founder" id="">Islamabad
<input type="radio" name="founder" id="">Karachi
<input type="radio" name="founder" id="">Hydrabad
<input type="radio" name="founder" id="">Lahore
</fieldset>
</div><br>
<br>
<br>
<button onclick="check()">Results</button>
<script src="app.js"></script>
</body>
</html>
Related
when the checkbox is checked by the user, I want to push the value(the numerical value are in the JS) for the checked box in an array, get the sum and display the total calories in the alert message.
here's my code so far:
var rice = 204;
var bread = 140;
var chicken = 147;
var beef = 282;
var carrots = 150;
var beans = 70;
function myFunction() {
var rice = document.getElementById("rice");
var bread = document.getElementById("bread");
var chicken = document.getElementById("chicken");
var beef = document.getElementById("beef");
var carrots = document.getElementById("carrots");
var beans = document.getElementById("beans");
const food = [];
if (rice.checked == true) {
food.push(window.rice);
} else if (bread.checked == true) {
food.push(window.bread);
} else if (chicken.checked == true) {
food.push(window.chicken);
} else if (beef.checked == true) {
food.push(window.beef);
} else if (carrots.checked == true) {
food.push(window.carrots);
} else if (beans.checked == true) {
food.push(window.beans);
}
let sum = food.reduce(function(a, b) {
return a + b;
}, 0);
console.log(sum); /*sum of array not working */
console.log(food);
}
myFunction();
<form>
<h2>Meal Plan</h2>
<h3>Dietary restrictions:</h3>
<input type="radio" name="diet" id="none" value="none" required>
<label for="none">None</label>
<br/><input type="radio" name="diet" id="vegetarian" value="vegetarian" required>
<label for="vegetarian">Vegetarian</label>
<br/><input type="radio" name="diet" id="lowcarb" value="lowcarb" required>
<label for="lowcarb">Low Carb</label>
<br />
<h3>Food items:</h3>
<input type="checkbox" name="Rice" id="rice" value="rice">
<label for="rice">Rice</label>
<br /><input type="checkbox" name="Beef" id="beef" value="beef">
<label for="beef">Beef</label>
<br /><input type="checkbox" name="Bread" id="bread" value="bread">
<label for="bread">Bread</label>
<br /><input type="checkbox" name="Beans" id="beans" value="beans">
<label for="beans">Beans</label>
<br /><input type="checkbox" name="Chicken" id="chicken" value="chicken">
<label for="chicken">Chicken</label>
<br /><input type="checkbox" name="Carrots" id="carrots" value="carrots">
<label for="carrots">Carrots</label>
<br /><br /><input type="submit" onclick="myFunction()" />
</form>
<script src="try.js"></script>
the values is not appending in the array when i check multuple boxes. it only appends the first box that i checked and doesn't include the next boxes. i cant get the sum, how can i fix that?
You can do this way
document.querySelector('form').addEventListener('click', e => {
if (e.target.matches('input[type="radio"]')) {
const checked = document.querySelector('#vegetarian').checked;
document.querySelectorAll('.meat').forEach(chk => {
chk.disabled = checked;
chk.checked = false;
});
}
});
const calories = {
rice: 204,
bread: 140,
chicken: 147,
beef: 282,
carrots: 150,
beans: 70
};
function myFunction() {
const food = [];
const veg = [];
let sum = 0;
document.querySelectorAll('input[type="checkbox"]').forEach(chk => {
if (chk.checked) {
food.push(chk.value);
if (chk.classList.contains('veg')) {
veg.push(chk.value);
}
sum += (calories[chk.value] || 0);
}
});
console.log(sum); /*sum of array not working */
alert(food);
if (veg.length < 2) {
alert('two vegs are recommendeded');
}
}
<!DOCTYPE html>
<html>
<head>
<title>Meal Plan</title>
</head>
<body>
<form onsubmit="return false;">
<h2>Meal Plan</h2>
<h3>Dietary restrictions:</h3>
<input type="radio" name="diet" id="none" value="none" required>
<label for="none">None</label>
<br/><input type="radio" name="diet" id="vegetarian" value="vegetarian" required>
<label for="vegetarian">Vegetarian</label>
<br/><input type="radio" name="diet" id="lowcarb" value="lowcarb" required>
<label for="lowcarb">Low Carb</label>
<br />
<h3>Food items:</h3>
<input type="checkbox" name="Rice" id="rice" value="rice">
<label for="rice">Rice</label>
<br /><input type="checkbox" name="Beef" class="meat" id="beef" value="beef">
<label for="beef">Beef</label>
<br /><input type="checkbox" name="Bread" id="bread" value="bread">
<label for="bread">Bread</label>
<br /><input type="checkbox" name="Beans" class="veg" id="beans" value="beans">
<label for="beans">Beans</label>
<br /><input type="checkbox" name="Chicken" class="meat" id="chicken" value="chicken">
<label for="chicken">Chicken</label>
<br /><input type="checkbox" name="Carrots" class="veg" id="carrots" value="carrots">
<label for="carrots">Carrots</label>
<br /><br /><input type="submit" onclick="myFunction()" />
</form>
</body>
</html>
Your existing if ... else if ... block got problem, it won't run the rest of else if once a condition is true.
do that this way ... (less code and more readability)
const
myForm = document.forms['my-form']
, calories =
{ rice : 204
, bread : 140
, chicken : 147
, beef : 282
, carrots : 150
, beans : 70
}
, NotVegetarianFood = ['beef', 'chicken' ]
;
myForm.oninput = e =>
{
if ( e.target.name === 'diet' )
{
let isVegetarian = (myForm.diet.value === 'vegetarian')
NotVegetarianFood.forEach( food =>
{
myForm[food].disabled = isVegetarian
if (isVegetarian)
myForm[food].checked = false
})
}
}
myForm.onsubmit = e =>
{
e.preventDefault()
let
sum = 0
, vegetables = 0
, formValues =
Array
.from(new FormData(myForm).entries() )
.reduce((res,[food,_])=>
{
if (!!calories[food])
{
vegetables += NotVegetarianFood.includes(food) ? 0 : 1
sum += calories[food]
res.push (food)
}
return res
},[])
myForm.message.textContent = (vegetables > 2)
? ''
: '2 vegetables options are recommended for a healthy meal regardless of the dietary restrictions.'
console.clear()
console.log( JSON.stringify( formValues), '\n-- calories sum =', sum )
}
fieldset {
width : 16em;
margin-bottom : .7em;
}
legend {
font-weight : bold;
}
label {
display : block;
margin-top : .4em;
}
<form name="my-form">
<h3>Meal Plan</h3>
<fieldset>
<legend>Dietary restrictions:</legend>
<label> <input type="radio" name="diet" value="none" checked > None </label>
<label> <input type="radio" name="diet" value="vegetarian" > vegetarian </label>
<label> <input type="radio" name="diet" value="lowcarb" > Low Carb </label>
</fieldset>
<fieldset>
<legend>Food items:</legend>
<label> <input type="checkbox" name="rice" > Rice </label>
<label> <input type="checkbox" name="beef" > Beef </label>
<label> <input type="checkbox" name="bread" > Bread </label>
<label> <input type="checkbox" name="beans" > Beans </label>
<label> <input type="checkbox" name="chicken" > Chicken </label>
<label> <input type="checkbox" name="carrots" > Carrots </label>
</fieldset>
<button type="submit">submit</button>
<output name="message"></output>
</form>
So based on the inputs in this questionnaire, a pop up message containing the score variable should be displayed by clicking the submit button. For some reason is not happening. Where exactly is the problem? In visual studio code there is no error showing up but when i complete the questionnaire in my browser and press submit nothing happens.
HTML
<!doctype html>
<html>
<head>
</head>
<body>
<h1>Endometrial Cancer Predictor </h1>
<h3>What is your BMI?</h3>
<input id="bmi1" type="radio" name="grp1" value="0"> less than 25 </input> <br>
<input id="bmi2" type="radio" name="grp1" value="1.85"> 25 to 29 </input> <br>
<input id="bmi3" type="radio" name="grp1" value="4.675"> 30 to 39 </input> <br>
<input id="bmi4" type="radio" name="grp1" value="6.175"> over 40 </input>
<h3>Do you take contraception?</h3>
<input id="contraNo" type="radio" name="grp2" value="0"> No <br>
<input id="contraOral" type="radio" name="grp2" value="-0.8"> Oral Contraception <br>
<input id="contraIud" type="radio" name="grp2" value="-1.2"> Intrauterine Device (IUD)
<h3>Do you take HRT?</h3>
<input id="hrtNo" type="radio" name="grp3" value="0"> No <br>
<input id="hrtConti" type="radio" name="grp3" value="-0.675"> Continuous <br>
<input id="hrtNon" type="radio" name="grp3" value="0.5"> Non Continuous
<h3>Do you suffer from Type 2 Diabetes?</h3>
<input id="diabYes" type="radio" name="grp4" value="1.375"> Yes <br>
<input id="diabNo" type="radio" name="grp4" value="0"> No
<h3>Do you suffer from PCOS?</h3>
<input id="pcosYes" type="radio" name="grp5" value="3.75"> Yes <br>
<input id="pcosNo" type="radio" name="grp5" value="0"> No
<h3>What is your parity?</h3>
<input id="nulliparity" type="radio" name="grp6" value="1.075"> 0 <br>
<input id="parOver1" type="radio" name="grp6" value="-0.8"> +1
<br>
<br>
<button id="btn1" onclick "fn1()">Submit </button>
<script>
src = "index.js"
</script>
</body>
</html>
index.js
function fn1()
{
var score=2.5;
var bmi1 = document.getElementById("bmi1");
var bmi2 = document.getElementById("bmi2");
var bmi3 = document.getElementById("bmi3");
var contraNo = document.getElementById("contraNo");
var contraOral = document.getElementById("contraOral");
var contraIud = document.getElementById("contraIud");
var hrtNo = document.getElementById("hrtNo");
var hrtConti = document.getElementById("hrtConti");
var hrtNon = document.getElementById("hrtNon");
var diabYes = document.getElementById("diabYes");
var diabNo = document.getElementById("diabNo");
var pcosYes = document.getElementById("pcosYes");
var pcosNo = document.getElementById("pcosNo");
var nulliparity = document.getElementById("nulliparity");
var parOver1 = document.getElementById("parOver1");
if(bmi1.checked==true)
score=score+bmi1.value;
else if(bmi2.checked==true)
score=score+bmi2.value;
else if(bmi3.checked==true)
score=score+bmi3.value;
else if(bmi4.checked==true)
score=score+bmi4.value;
if(contraNo.checked==true)
score=score+contraNo.value;
else if(contraOral.checked==true)
score=score+contraOral.value;
else if(contraIud.checked==true)
score=score+contraIud.value;
if(hrtNo.checked==true)
score=score+hrtNo.value;
else if(hrtConti.checked==true)
score=score+hrtConti.value;
else if(hrtNon.checked==true)
score=score+hrtNon.value;
if(diabYes.checked==true)
score=score+diabYes.value;
else if(diabNo.checked==true)
score=score+diabNo.value;
if(pcosYes.checked==true)
score=score+pcosYes.value;
else if(pcosNo.checked==true)
score=score+pcosNo.value;
if(nulliparity.checked==true)
score=score+nulliparity.value;
else if(parOver1.checked==true)
score=score+parOver1.value;
return score;
}
function displayResult() {
var result = fn1();
document.getElementById('btn1').innerHTML = result;
return false;
}
According to your code snippet, I assume you need to run displayResult() function onclick. fn1() is not doing any alerting or DOM manipulation, just returning the value of score. Check the slightly updated demo attached to this answer below.
Also if you wish to display the result in a pop up, you need to use alert() function inside displayResult()
function fn1() {
var score = 2.5;
var bmi1 = document.getElementById("bmi1");
var bmi2 = document.getElementById("bmi2");
var bmi3 = document.getElementById("bmi3");
var contraNo = document.getElementById("contraNo");
var contraOral = document.getElementById("contraOral");
var contraIud = document.getElementById("contraIud");
var hrtNo = document.getElementById("hrtNo");
var hrtConti = document.getElementById("hrtConti");
var hrtNon = document.getElementById("hrtNon");
var diabYes = document.getElementById("diabYes");
var diabNo = document.getElementById("diabNo");
var pcosYes = document.getElementById("pcosYes");
var pcosNo = document.getElementById("pcosNo");
var nulliparity = document.getElementById("nulliparity");
var parOver1 = document.getElementById("parOver1");
if (bmi1.checked == true)
score = score + bmi1.value;
else if (bmi2.checked == true)
score = score + bmi2.value;
else if (bmi3.checked == true)
score = score + bmi3.value;
else if (bmi4.checked == true)
score = score + bmi4.value;
if (contraNo.checked == true)
score = score + contraNo.value;
else if (contraOral.checked == true)
score = score + contraOral.value;
else if (contraIud.checked == true)
score = score + contraIud.value;
if (hrtNo.checked == true)
score = score + hrtNo.value;
else if (hrtConti.checked == true)
score = score + hrtConti.value;
else if (hrtNon.checked == true)
score = score + hrtNon.value;
if (diabYes.checked == true)
score = score + diabYes.value;
else if (diabNo.checked == true)
score = score + diabNo.value;
if (pcosYes.checked == true)
score = score + pcosYes.value;
else if (pcosNo.checked == true)
score = score + pcosNo.value;
if (nulliparity.checked == true)
score = score + nulliparity.value;
else if (parOver1.checked == true)
score = score + parOver1.value;
return score;
}
function displayResult() {
var result = fn1();
document.getElementById('btn1').innerHTML = result;
alert(result);
return false;
}
<h1>Endometrial Cancer Predictor </h1>
<h3>What is your BMI?</h3>
<input id="bmi1" type="radio" name="grp1" value="0"> less than 25 <br>
<input id="bmi2" type="radio" name="grp1" value="1.85"> 25 to 29<br>
<input id="bmi3" type="radio" name="grp1" value="4.675"> 30 to 39 <br>
<input id="bmi4" type="radio" name="grp1" value="6.175"> over 40
<h3>Do you take contraception?</h3>
<input id="contraNo" type="radio" name="grp2" value="0"> No <br>
<input id="contraOral" type="radio" name="grp2" value="-0.8"> Oral Contraception <br>
<input id="contraIud" type="radio" name="grp2" value="-1.2"> Intrauterine Device (IUD)
<h3>Do you take HRT?</h3>
<input id="hrtNo" type="radio" name="grp3" value="0"> No <br>
<input id="hrtConti" type="radio" name="grp3" value="-0.675"> Continuous <br>
<input id="hrtNon" type="radio" name="grp3" value="0.5"> Non Continuous
<h3>Do you suffer from Type 2 Diabetes?</h3>
<input id="diabYes" type="radio" name="grp4" value="1.375"> Yes <br>
<input id="diabNo" type="radio" name="grp4" value="0"> No
<h3>Do you suffer from PCOS?</h3>
<input id="pcosYes" type="radio" name="grp5" value="3.75"> Yes <br>
<input id="pcosNo" type="radio" name="grp5" value="0"> No
<h3>What is your parity?</h3>
<input id="nulliparity" type="radio" name="grp6" value="1.075"> 0 <br>
<input id="parOver1" type="radio" name="grp6" value="-0.8"> +1
<br>
<br>
<button id="btn1" onclick="displayResult()">Submit</button>
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...
new to stack overflow here. My question is what I might have done wrong with this quiz reset button? I have it set so that if the reset button is clicked at the end of the quiz, the quiz should return to the first question. However, the button is doing nothing. I was thinking I may have variable scope issues but I tried to accommodate for that and I still can't get the reset button to work. Thanks in advance.
HTML:
<html>
<head>
<title>Hello...</title>
</head>
<body>
<h1 id="theTitle" class="highlight summer">BATMAN QUIZ!</h1>
<div id="mainContent">
<div id="question">
</div>
<div id="choices">
<input type="radio" name="choices" /><label id="choice1" class="radios"></label></br>
<input type="radio" name="choices" /><label id="choice2" class="radios"></label></br>
<input type="radio" name="choices" /><label id="choice3" class="radios"></label></br>
<input type="submit" id="submitButton" value="Submit" /></br>
<input type="submit" class="hidden" id="nextButton" value="Next Question" />
</div>
<div class="hidden" id="answer">
</div>
</div>
</body>
</html>
CSS:
.hidden{
display:none;
}
.visible{
display:inline;
}
JavaScript:
var questionArray = [
["What is Batman's first name?", "Bruce Wayne"],
["What city does Batman live in?", "Gotham"],
["What is Commisioner Gordon's daughter's name?", "Barbara"]
];
var choicesArray = [
["Bruce Wayne", "Clark Kent", "Charles Xavier"],
["Metropolis", "Starling City", "Gotham"],
["Helen", "Barbara", "Jean"]
]
i = 0;
theQuiz(i);
function theQuiz(i) {
if (i < questionArray.length) {
var score = 0;
document.querySelector("#question").textContent = questionArray[i][0];
document.querySelector("#answer").textContent = "The correct answer is: " + questionArray[i][1];
document.querySelector("#choice1").textContent = choicesArray[i][0];
document.querySelector("#choice2").textContent = choicesArray[i][1];
document.querySelector("#choice3").textContent = choicesArray[i][2];
var answer = document.querySelector("#answer");
var submitButton = document.querySelector("#submitButton")
submitButton.addEventListener("click", showAnswer, false);
var nextButton = document.querySelector("#nextButton")
nextButton.addEventListener("click", nextQuestion, false);
function showAnswer() {
answer.classList.add("visible");
nextButton.classList.add("visible");
};
function nextQuestion() {
answer.classList.remove("visible");
nextButton.classList.remove("visible");
i++;
theQuiz(i);
};
} else {
document.body.textContent = "Game Over!";
var restartButton = document.createElement("input")
restartButton.type = "submit";
restartButton.value = "Play Again!"
document.body.appendChild(restartButton);
i=0;
theQuiz(i);
restartButton.addEventListener("click", resetGame, true);
function resetGame() {
i = 0;
theQuiz(0);
};
}
};
If you want to refresh the whole page: location.reload();
If you want to reset just where you are at on the quiz:
Wrap the whole quiz in a <form> and add this <input type='reset'> that's it.
Added and changed the following:
Required
button#fullReset and EventListeneradded
#mainContent into a <form>
<input type='reset'>added
Recommended
#choices to a <fieldset>
#theTitle inside <legend>
#answer into a <input type='hidden'>
Specification
id on <label> are useless, follow this pattern:
<label for='rad1'>Radio 1</label>
<input id='rad1' name='rads'>
Either <br> or <br/> never </br>
SNIPPET
<html>
<head>
<title>Hello...</title>
</head>
<body>
<form id="mainContent">
<fieldset id="choices">
<legend>
<h1 id="theTitle" class="highlight summer">BATMAN QUIZ!</h1>
</legend>
<input type="radio" name="choices" />
<label id="choice1" class="radios"></label>
<br>
<input type="radio" name="choices" />
<label id="choice2" class="radios"></label>
<br>
<input type="radio" name="choices" />
<label id="choice3" class="radios"></label>
<br>
<input type="submit" id="submitButton" value="Submit" />
<br>
<input type="submit" class="hidden" id="nextButton" value="Next Question" />
<input type="hidden" id="answer">
<input type='reset'>
<button id='fullReset'>Full Reset</button>
</fieldset>
</form>
<script>
var fullReset = document.getElementById('fullReset');
fullReset.addEventListener('click', function(e) {
location.reload();
}, false);
</script>
</body>
</html>
On clicking submit I want the score and the correct answers to be printed on a new page. Right now the score pops up on an alert box. How can this be done in HTML/JavaScript ?
The code for my quiz application is :
<html>
<head>
<title>Quizzer</title>
<style type="text/css">
body {
background:#E3E1DC;
font-size:16px;
font-family:Helvetica, Arial;
line-height:1.2em;
color:#222222;
}
pre {
font-family:Consolas, Courier;
font-size: 12px;
color:#444444;
line-height:12px;
margin-left:30px;
margin-top:-28px;
}
.instructions {
margin-left:25px;
}
.button {
margin-left:10px;
margin-bottom:120px;
width:200px;
height:50px;
}
.question {
background:#F1E6D4;
padding:15px;
margin:10px;
}
.odd {
background:#9F9694;
}
.wrong {
border-left:#BA3D49 5px solid;
padding-left:10px;
}
</style>
<script langauge="JavaScript">
// number of questions in the quiz, this must be set exactly
var totalQuestions = 5;
// arrays to store answers, and user submited answers.
var answers = new Array;
var userAnswers = new Array;
// quiz answers
answers[1] = "B";
answers[2] = "C";
answers[3] = "D";
answers[4] = "D";
answers[5] = "B";
// sets the users answer selection to the appropriate array element
// in the userAnswers array.
// questionNumber is the question div id as well as the userAnswers
// array element index to store the answer in.
// answerSelection is the value of the selected answer from a question
function SetAnswer(questionNumber, answerSelection) {
userAnswers[questionNumber] = answerSelection;
}
// applies the .wrong class styling to any question div that is incorrect
function MarkIncorrectQuestions() {
for(i = 1; i <= totalQuestions; i++) {
if(answers[i] != userAnswers[i]) {
document.getElementById(i).className += " wrong";
}
}
}
// counts the number of correct answers
// returns the number of correct answers
function GetScore() {
var score = 0;
for(i = 1; i <= totalQuestions; i++) {
if(userAnswers[i] == answers[i])
score++;
}
return score;
}
// sets classes for each question div to its default styling.
function ApplyDefaultQuestionStyles() {
for(i = 1; i <= totalQuestions; i++) {
if(i % 2 == 0) {
document.getElementById(i).className = "question";
}
else {
document.getElementById(i).className = "question odd";
}
}
}
// calls all appropriate functions in order to check answers and mark
// incorrect questions.
function CheckQuiz() {
ApplyDefaultQuestionStyles();
var totalQuestions = '5';
var score = GetScore();
MarkIncorrectQuestions();
alert("You scored: " + score + " out of " + totalQuestions + ".");
//document.write("<h1>hello</h1>");
}
function result(score,totalQuestions){
document.write("Score" +score);
}
</script>
</head>
<body onLoad="ApplyDefaultQuestionStyles()">
<div class="instructions">
<h1>The Movie Quiz</h1>
</div>
<form>
<div id="1">
<p><strong>Question 1</strong></p>
<p>Where does “It’s a Wonderful Life” take place?</p>
<p><input type="radio" value="A" onClick="SetAnswer(1, this.value)" name="radiobutton2">Bedford Hills</p>
<p><input type="radio" value="B" onClick="SetAnswer(1, this.value)" name="radiobutton2">Bedford Falls</p>
<p><input type="radio" value="C" onClick="SetAnswer(1, this.value)" name="radiobutton2">Bedford Lake</p>
<p><input type="radio" value="D" onClick="SetAnswer(1, this.value)" name="radiobutton2">Bedford City</p>
</div>
<div id="2">
<p><strong>Question 2</strong></p>
<p>In “The Godfather,” who was murdered in the causeway?</p>
<p><input type="radio" value="A" onClick="SetAnswer(2, this.value)" name="radiobutton2">Luca Brasi</p>
<p><input type="radio" value="B" onClick="SetAnswer(2, this.value)" name="radiobutton2">Moe Greene</p>
<p><input type="radio" value="C" onClick="SetAnswer(2, this.value)" name="radiobutton2">Sonny</p>
<p><input type="radio" value="D" onClick="SetAnswer(2, this.value)" name="radiobutton2">Paulie</p>
</div>
<div id="3">
<p><strong>Question 3</strong></p>
<p>Where did Princess Leia hide the stolen plans for the Death Star?</p>
<p><input type="radio" value="A" onClick="SetAnswer(3, this.value)" name="radiobutton2">In C-3PO</p>
<p><input type="radio" value="B" onClick="SetAnswer(3, this.value)" name="radiobutton2">In a pocket in the hem of her white gown</p>
<p><input type="radio" value="C" onClick="SetAnswer(3, this.value)" name="radiobutton2">In the Millennium Falcon</p>
<p><input type="radio" value="D" onClick="SetAnswer(3, this.value)" name="radiobutton2">In R2-D2</p>
</div>
<div id="4">
<p><strong>Question 4</strong></p>
<p>In which of the following films did Robert Duvall NOT appear?</p>
<p><input type="radio" value="A" onClick="SetAnswer(4, this.value)" name="radiobutton2">To Kill a Mockingbird</p>
<p><input type="radio" value="B" onClick="SetAnswer(4, this.value)" name="radiobutton2">The Godfather</p>
<p><input type="radio" value="C" onClick="SetAnswer(4, this.value)" name="radiobutton2">Tender Mercies</p>
<p><input type="radio" value="D" onClick="SetAnswer(4, this.value)" name="radiobutton2">One Flew Over the Cuckoo’s Nest</p>
</div>
<div id="5">
<p><strong>Question 5</strong></p>
<p>Who was Scarlett O’Hara’s second husband?</p>
<p><input type="radio" value="A" onClick="SetAnswer(5, this.value)" name="radiobutton2">Frank Kennedy</p>
<p><input type="radio" value="B" onClick="SetAnswer(5, this.value)" name="radiobutton2">Rhett Butler</p>
<p><input type="radio" value="C" onClick="SetAnswer(5, this.value)" name="radiobutton2">Ashley Wilkes</p>
<p><input type="radio" value="D" onClick="SetAnswer(5, this.value)" name="radiobutton2">Charles Hamilton</p>
</div>
<p>
<input type="submit" class="ui-button" onClick="CheckQuiz()" value="Submit Answers" name="submitButton" class="button"></p>
</form>
</body>
You have two options instead of using an alert ...
1) Create a layered popup that pops up in front of all your page content (you could darken the BG as well like most modals do). This would allow you to pop the message up in the same page and not require the user to open another window.
2) Your other option would be to popup a new window and use javascript to write the information to that window. See the following link for more information on this: http://www.electrictoolbox.com/write-content-dynamic-javascript-popup/
I personally would go with the first because it guarantees that it will work even if the user has a popup blocker.