I want to make a questionnaire that asks questions then has a button at the end of the page called "display answers" which will show the user which answers they got correct.
If I were to use this question for example:
<p class="question">1. What is the answer to this question?</p>
<ul class="answers">
<input type="radio" name="q1" value="a" id="q1a"><label for="q1a">Answer 1</label><br/>
<input type="radio" name="q1" value="b" id="q1b"><label for="q1b">Answer 2</label><br/>
<input type="radio" name="q1" value="c" id="q1c"><label for="q1c">Answer 3</label><br/>
<input type="radio" name="q1" value="d" id="q1d"><label for="q1d">Answer 4</label><br/>
</ul>
How would I go about creating a button for this code that when pressed, tells if the answer is correct or not?
<p class="question">1. What is the answer to this question?</p>
<ul id="answers" class="answers">
<input type="radio" name="q1" value="a" id="q1a"><label for="q1a">Answer 1</label><br/>
<input type="radio" name="q1" value="b" id="q1b"><label for="q1b">Answer 2</label><br/>
<input type="radio" name="q1" value="c" id="q1c"><label for="q1c">Answer 3</label><br/>
<input type="radio" name="q1" value="d" id="q1d"><label for="q1d">Answer 4</label><br/>
<input type="button" value="submit" onClick="showAnswer()" />
</ul>
<span id="info"></span>
Then add a script above that piece of code:
<script>
function showAnswer(){
if(document.getElementById('q1a').checked){
document.getElementById('info').innerHTML = "Correct!";
}else{
document.getElementById('info').innerHTML = "Incorrect!";
}
}
</script>
I don't know the answer to your quiz, so answer 1 is correct in this case.
Two .addEventListeners()
One on the container that holds all of the questions and answers (e.g. #QA1)
The other on the button used when finished with the quiz (e.g. #btn1)
When the user picks an answer, #QA1 will listen for any clicks on any radio button (e.g. .answers). Using a single event listener for multiple event.targets (i.e. the element clicked) is far more efficient than adding one on each radio button. Through comparing what was actually clicked (radio button) and what was the element with the listener, we'll can get the radio button's id. See this article for details.
Once the id of the clicked radio button is determined (see previous reference), it's pushed to an array (e.g. answers[]).
When the user is done, he/she clicks the "DONE" button, triggering the click event of #btn1.
A for loop is used to iterate over the answer[] and key[] arrays. On each iteration (i.e.loop,) the two are compared for matching elements.
The results are printed on #out1 which is an <output> element nested in an ordered list (<ol>).
Snippet
var qa = document.getElementById('QA1');
var btn1 = document.getElementById('btn1');
var answers = [];
var key = ['q1c', 'q2a', 'q3d'];
qa.addEventListener('click', function(event) {
if (event.target != event.currentTarget) {
var choice = event.target.id;
answers.push(choice);
}
event.stopPropagation();
}, false);
btn1.addEventListener('click', function(event) {
event.preventDefault();
var qList = document.getElementsByClassName('question');
var out1 = document.getElementById('out1');
for (var i = 0; i < qList.length; i++) {
if (answers[i] === key[i]) {
out1.innerHTML += '<li>' + answers[i] + ' is correct</li>';
} else {
out1.innerHTML += '<li>' + answers[i] + ' is incorrect, the correct answer is ' + key[i] + '</li>';
}
}
}, false);
body {
font: 400 16px/1.45'Verdana';
}
* {
font: inherit;
}
.question {
margin-bottom: 15px;
}
.answers {
list-style: none;
}
.answers li {
margin-left: -15px;
}
input[type="radio"] {
position: relative;
top: 2.25px;
}
#btn1 a {
text-decoration: none;
}
#out1 {
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
<ol id="QA1" class="QA">
<li id="q1" class="question">What is the answer to this question?
<ol class="answers">
<li>a.
<input type="radio" name="q1" value="a" id="q1a" />
<label for="q1a">Answer</label>
</li>
<li>b.
<input type="radio" name="q1" value="b" id="q1b" />
<label for="q1b">Answer</label>
</li>
<li>c.
<input type="radio" name="q1" value="c" id="q1c" />
<label for="q1c">Answer</label>
</li>
<li>d.
<input type="radio" name="q1" value="d" id="q1d" />
<label for="q1d">Answer</label>
</li>
</ol>
<!--answers-->
</li>
<!--question-->
<li id="q2" class="question">What is the answer to this question?
<ol class="answers">
<li>a.
<input type="radio" name="q2" value="a" id="q2a" />
<label for="q2a">Answer</label>
</li>
<li>b.
<input type="radio" name="q2" value="b" id="q2b" />
<label for="q2b">Answer</label>
</li>
<li>c.
<input type="radio" name="q2" value="c" id="q2c" />
<label for="q2c">Answer</label>
</li>
<li>d.
<input type="radio" name="q2" value="d" id="q2d" />
<label for="q2d">Answer</label>
</li>
</ol>
<!--answers-->
</li>
<!--question-->
<li id="q3" class="question">What is the answer to this question?
<ol class="answers">
<li>a.
<input type="radio" name="q3" value="a" id="q3a" />
<label for="q3a">Answer</label>
</li>
<li>b.
<input type="radio" name="q3" value="b" id="q3b" />
<label for="q3b">Answer</label>
</li>
<li>c.
<input type="radio" name="q3" value="c" id="q3c" />
<label for="q3c">Answer</label>
</li>
<li>d.
<input type="radio" name="q3" value="d" id="q3d" />
<label for="q3d">Answer</label>
</li>
</ol>
<!--answers-->
</li>
<!--question-->
</ol>
<!--QA-->
<button id="btn1">DONE
</button>
<ol>
<output id="out1"></output>
</ol>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Questionare</title>
</head>
<body>
<p>1. What is the answer to this question?</p>
<ul onclick="man()">
<input type="radio" name="q1" value="a">Answer 1<br/> <input type="radio" name="q1" value="b">Answer 2<br/>
<input type="radio" name="q1" value="c">Answer 3<br/>
<input type="radio" name="q1" value="d">Answer 4<br/>
</ul>
<p id="m"></p>
<script>
var man = function(){
document.getElementById("m").innerHTML = 'The correct answer is: Answer 1';
}
</script>
</body>
</html>
Here is what u want, done in simplest way, using CSS Document object model, for reference go here HTML CSS DOM
Related
I am new to javaScript and am confused on how I should get the total from the checked radio boxes. Also I am trying to add a submit button for the user, so that the total will only be revealed after they click submit. I feel as though I may not be parsing the values properly?
Appreciate the help
Thanks!
<html>
<head>
<script>
function calculateTotal() {
var score = 0;
q1 = new Array(1,2,3,4,5);
q2 = new Array(1,2,3,4,5);
q3 = new Array(1,2,3,4,5);
q4 = new Array(1,2,3,4,5);
q5 = new Array(1,2,3,4,5);
for (var i = 0; i < q1.length; i++ ) {
if(q1[i].checked){
score += parseFloat(q1[i].value);
}
for(var c = 0; c < q2.length; c++){
if(q2[i].checked){
score += parseFloat(q2[i].value);
}
for(var c = 0; c < q3.length; c++){
if(q3[i].checked){
score += parseFloat(q3[i].value);
}
for(var c = 0; c < q4.length; c++){
if(q4[i].checked){
score += parseFloat(q4[i].value);
}
for(var c = 0; c < q5.length; c++){
if(q5[i].checked){
score += parseFloat(q5[i].value);
}
}
}
}
}
}
}
</script>
</head>
<p class="question">1. Rate your family life?</p>
<ul class="answers">
<input type="radio" name="q1" value="a" id="q1a"><label for="q1a">1</label>
<br/>
<input type="radio" name="q1" value="b" id="q1b"><label for="q1b">2</label>
<br/>
<input type="radio" name="q1" value="c" id="q1c"><label for="q1c">3</label>
<br/>
<input type="radio" name="q1" value="d" id="q1d"><label for="q1d">4</label>
<br/>
<input type="radio" name="q1" value="e" id="q1e"><label for="q1e">5</label>
<br/>
</ul>
<p class="question">2. Rate your romantic life?</p>
<ul class="answers">
<input type="radio" name="q2" value="a" id="q2a"><label for="q2a">1</label>
<br/>
<input type="radio" name="q2" value="b" id="q2b"><label for="q2b">2</label>
<br/>
<input type="radio" name="q2" value="c" id="q2c"><label for="q2c">3</label>
<br/>
<input type="radio" name="q2" value="d" id="q2d"><label for="q2d">4</label>
<br/>
<input type="radio" name="q2" value="e" id="q2e"><label for="q2e">5</label>
<br/>
</ul>
<p class="question">3. Rate your social life?</p>
<ul class="answers">
<input type="radio" name="q3" value="a" id="q3a"><label for="q3a">1</label>
<br/>
<input type="radio" name="q3" value="b" id="q3b"><label for="q3b">2</label>
<br/>
<input type="radio" name="q3" value="c" id="q3c"><label for="q3c">3</label>
<br/>
<input type="radio" name="q3" value="d" id="q3d"><label for="q3d">4</label>
<br/>
<input type="radio" name="q3" value="e" id="q3e"><label for="q3e">5</label>
<br/>
</ul>
<p class="question">4. Rate your career/academic life?</p>
<ul class="answers">
<input type="radio" name="q4" value="a" id="q4a"><label for="q4a">1</label>
<br/>
<input type="radio" name="q4" value="b" id="q4b"><label for="q4b">2</label>
<br/>
<input type="radio" name="q4" value="c" id="q4c"><label for="q4c">3</label>
<br/>
<input type="radio" name="q4" value="d" id="q4d"><label for="q4d">4</label>
<br/>
<input type="radio" name="q4" value="e" id="q4e"><label for="q4e">5</label>
<br/>
</ul>
<p class="question">5. Rate how you physically feel (e.g. lethargic 1 to
energetic 5)?</p>
<ul class="answers">
<input type="radio" name="q5" value="a" id="q5a"><label for="q5a">1</label>
<br/>
<input type="radio" name="q5" value="b" id="q5b"><label for="q5b">2</label>
<br/>
<input type="radio" name="q5" value="c" id="q5c"><label for="q5c">3</label>
<br/>
<input type="radio" name="q5" value="d" id="q5d"><label for="q5d">4</label>
<br/>
<input type="radio" name="q5" value="d" id="q5e"><label for="q5e">5</label>
<br/>
</ul>
<script>
alert("Your overall score is " + calculateTotal());
</script>
What you want to do is to get your checkboxes as arrays, not create some unrelated arrays yourself. That can be done using document.getElementsByName("q1");
function calculateTotal() {
var score = 0;
q1 = document.getElementsByName("q1");
q2 = document.getElementsByName("q2");
q3 = document.getElementsByName("q3");
q4 = document.getElementsByName("q4");
q5 = document.getElementsByName("q5");
for (var i = 0; i < q1.length; i++ ) {
if(q1[i].checked){
score += parseFloat(q1[i].value);
}
for(var c = 0; c < q2.length; c++){
if(q2[i].checked){
score += parseFloat(q2[i].value);
}
for(var c = 0; c < q3.length; c++){
if(q3[i].checked){
score += parseFloat(q3[i].value);
}
for(var c = 0; c < q4.length; c++){
if(q4[i].checked){
score += parseFloat(q4[i].value);
}
for(var c = 0; c < q5.length; c++){
if(q5[i].checked){
score += parseFloat(q5[i].value);
}
}
}
}
}
}
}
EDIT: Oh, and for the button to calculate the checked values by the user, you can do really easy something like:
<div onClick="calculateTotal();"> Calculate total </div>
You add a button, attach an event handler to that button, and calculate the total
document.getElementById('total').addEventListener('click', calculateTotal);
function calculateTotal() {
var els = document.querySelectorAll('input[type=radio][name^=q]:checked');
var val = [].map.call(els, function(el) {
return "abcde".split('').indexOf(el.value) + 1;
});
var tot = val.reduce(function(a, b) {
return a + b
});
alert(tot);
}
<p class="question">1. Rate your family life?</p>
<ul class="answers">
<input type="radio" name="q1" value="a" id="q1a"><label for="q1a">1</label>
<br/>
<input type="radio" name="q1" value="b" id="q1b"><label for="q1b">2</label>
<br/>
<input type="radio" name="q1" value="c" id="q1c"><label for="q1c">3</label>
<br/>
<input type="radio" name="q1" value="d" id="q1d"><label for="q1d">4</label>
<br/>
<input type="radio" name="q1" value="e" id="q1e"><label for="q1e">5</label>
<br/>
</ul>
<p class="question">2. Rate your romantic life?</p>
<ul class="answers">
<input type="radio" name="q2" value="a" id="q2a"><label for="q2a">1</label>
<br/>
<input type="radio" name="q2" value="b" id="q2b"><label for="q2b">2</label>
<br/>
<input type="radio" name="q2" value="c" id="q2c"><label for="q2c">3</label>
<br/>
<input type="radio" name="q2" value="d" id="q2d"><label for="q2d">4</label>
<br/>
<input type="radio" name="q2" value="e" id="q2e"><label for="q2e">5</label>
<br/>
</ul>
<p class="question">3. Rate your social life?</p>
<ul class="answers">
<input type="radio" name="q3" value="a" id="q3a"><label for="q3a">1</label>
<br/>
<input type="radio" name="q3" value="b" id="q3b"><label for="q3b">2</label>
<br/>
<input type="radio" name="q3" value="c" id="q3c"><label for="q3c">3</label>
<br/>
<input type="radio" name="q3" value="d" id="q3d"><label for="q3d">4</label>
<br/>
<input type="radio" name="q3" value="e" id="q3e"><label for="q3e">5</label>
<br/>
</ul>
<p class="question">4. Rate your career/academic life?</p>
<ul class="answers">
<input type="radio" name="q4" value="a" id="q4a"><label for="q4a">1</label>
<br/>
<input type="radio" name="q4" value="b" id="q4b"><label for="q4b">2</label>
<br/>
<input type="radio" name="q4" value="c" id="q4c"><label for="q4c">3</label>
<br/>
<input type="radio" name="q4" value="d" id="q4d"><label for="q4d">4</label>
<br/>
<input type="radio" name="q4" value="e" id="q4e"><label for="q4e">5</label>
<br/>
</ul>
<p class="question">5. Rate how you physically feel (e.g. lethargic 1 to energetic 5)?</p>
<ul class="answers">
<input type="radio" name="q5" value="a" id="q5a"><label for="q5a">1</label>
<br/>
<input type="radio" name="q5" value="b" id="q5b"><label for="q5b">2</label>
<br/>
<input type="radio" name="q5" value="c" id="q5c"><label for="q5c">3</label>
<br/>
<input type="radio" name="q5" value="d" id="q5d"><label for="q5d">4</label>
<br/>
<input type="radio" name="q5" value="d" id="q5e"><label for="q5e">5</label>
<br/>
</ul>
<button id="total">Total</button>
Here is a working example. You will want to change the value="" to the value you want to add. the document.getElementsByNames("").value will get this value. Also your for loops are all nested which you don't want to do.
You can add a button with an onclick method to call the method you want. since all the values have the same length you can get away with just one for loop. You also probably want to add a tag for your html body.
function calculateTotal() {
var score = 0;
q1 = document.getElementsByName("q1");
q2 = document.getElementsByName("q2");
q3 = document.getElementsByName("q3");
q4 = document.getElementsByName("q4");
q5 = document.getElementsByName("q5");
for (var i = 0; i < q1.length; i++) {
if (q1[i].checked) {
score += parseFloat(q1[i].value);
}
if (q2[i].checked) {
score += parseFloat(q2[i].value);
}
if (q3[i].checked) {
score += parseFloat(q3[i].value);
}
if (q4[i].checked) {
score += parseFloat(q4[i].value);
}
if (q5[i].checked) {
score += parseFloat(q5[i].value);
}
}
return score;
}
Here is what one of the radio buttons should look like.
1. Rate your family life?
<ul class="answers">
<input type="radio" name="q1" value="1" id="q1a"><label for="q1a">1</label>
<br/>
<input type="radio" name="q1" value="2" id="q1b"><label for="q1b">2</label>
<br/>
<input type="radio" name="q1" value="3" id="q1c"><label for="q1c">3</label>
<br/>
<input type="radio" name="q1" value="4" id="q1d"><label for="q1d">4</label>
<br/>
<input type="radio" name="q1" value="5" id="q1e"><label for="q1e">5</label>
<br/>
</ul>
<p class="question">2. Rate your romantic life?</p>
<ul class="answers">
<input type="radio" name="q2" value="1" id="q2a"><label for="q2a">1</label>
<br/>
<input type="radio" name="q2" value="2" id="q2b"><label for="q2b">2</label>
<br/>
<input type="radio" name="q2" value="3" id="q2c"><label for="q2c">3</label>
<br/>
<input type="radio" name="q2" value="4" id="q2d"><label for="q2d">4</label>
<br/>
<input type="radio" name="q2" value="5" id="q2e"><label for="q2e">5</label>
<br/>
</ul>
<p class="question">3. Rate your social life?</p>
<ul class="answers">
<input type="radio" name="q3" value="1" id="q3a"><label for="q3a">1</label>
<br/>
<input type="radio" name="q3" value="2" id="q3b"><label for="q3b">2</label>
<br/>
<input type="radio" name="q3" value="3" id="q3c"><label for="q3c">3</label>
<br/>
<input type="radio" name="q3" value="4" id="q3d"><label for="q3d">4</label>
<br/>
<input type="radio" name="q3" value="5" id="q3e"><label for="q3e">5</label>
<br/>
</ul>
<p class="question">4. Rate your career/academic life?</p>
<ul class="answers">
<input type="radio" name="q4" value="1" id="q4a"><label for="q4a">1</label>
<br/>
<input type="radio" name="q4" value="2" id="q4b"><label for="q4b">2</label>
<br/>
<input type="radio" name="q4" value="3" id="q4c"><label for="q4c">3</label>
<br/>
<input type="radio" name="q4" value="4" id="q4d"><label for="q4d">4</label>
<br/>
<input type="radio" name="q4" value="5" id="q4e"><label for="q4e">5</label>
<br/>
</ul>
<p class="question">5. Rate how you physically feel (e.g. lethargic 1 to energetic 5)?</p>
<ul class="answers">
<input type="radio" name="q5" value="1" id="q5a"><label for="q5a">1</label>
<br/>
<input type="radio" name="q5" value="2" id="q5b"><label for="q5b">2</label>
<br/>
<input type="radio" name="q5" value="3" id="q5c"><label for="q5c">3</label>
<br/>
<input type="radio" name="q5" value="4" id="q5d"><label for="q5d">4</label>
<br/>
<input type="radio" name="q5" value="5" id="q5e"><label for="q5e">5</label>
<br/>
</ul>
<button type="submit" onclick="alert(calculateTotal())">Submit</button>
The main reason your provided code didn't work was because you forgot to return the calculated score from your function:
function calculateScore() {
// your code...
return score;
}
You also need to make sure each of your loops is closed, with a curly brace, before starting the next one.
However, the most readable way to get the value of a group of radio boxes is to use a form element like so:
function calculateScore() {
var formElement = document.getElementById("the-form"),
score = 0;
score += parseInt(formElement.q1.value);
score += parseInt(formElement.q2.value);
return score;
}
function displayScore() {
document.getElementById("the-score").innerText = calculateScore();
}
<form id="the-form">
<input type="radio" name="q1" value=1 id="q1-a1"><label for="q1-a1">1</label>
<input type="radio" name="q1" value=2 id="q1-a2"><label for="q1-a2">2</label>
<input type="radio" name="q1" value=3 id="q1-a3"><label for="q1-a3">3</label>
<input type="radio" name="q1" value=4 id="q1-a4"><label for="q1-a4">4</label>
<input type="radio" name="q1" value=5 id="q1-a5"><label for="q1-a5">5</label>
<br>
<br>
<input type="radio" name="q2" value=1 id="q2-a1"><label for="q2-a1">1</label>
<input type="radio" name="q2" value=2 id="q2-a2"><label for="q2-a2">2</label>
<input type="radio" name="q2" value=3 id="q2-a3"><label for="q2-a3">3</label>
<input type="radio" name="q2" value=4 id="q2-a4"><label for="q2-a4">4</label>
<input type="radio" name="q2" value=5 id="q2-a5"><label for="q2-a5">5</label>
</form>
<button onclick="displayScore()">Calculate Score</button>
<br>
<output id="the-score"></output>
The form element contains properties named after the name tags of each of the inputs within the form and their values can be accessed with the value property.
By changing the values from a..e to 1..5 the code can be simpler.
I have the following code in which there are 5 questions. I want that all 5 questions should be answered, in case any questions is not filled, user gets validation.
question 1
<ul class="option">
<li> <input type="radio" name="question1" id="sd1" value="1">Strongly Disagree</li>
<li> <input type="radio" name="question1" id="d1" value="2">Disagree</li>
<input type="radio" name="question1" id="n1" value="3">Neither Agree Nor Dis<li>agree</li>
<li> <input type="radio" name="question1" id="a1" value="4">Agree</li>
<li> <input type="radio" name="question1" id="sa1" value="5">Strongly Agree
</li></ul>
<br/><br/>
question 2
<ul class="option">
<li> <input type="radio" name="question2" id="sd2" value="1">Strongly Disagree</li>
<li> <input type="radio" name="question2" id="d2" value="2">Disagree</li>
<li> <input type="radio" name="question2" id="n2" value="3">Neither Agree Nor Disagree</li>
<li> <input type="radio" name="question2" id="a2" value="4">Agree</li?
<li> <input type="radio" name="question2" id="sa2" value="5">Strongly Agree
</li></ul>
<br/><br/>
javascript code is
// Delegate submit action
$(document).on('submit', 'form', function () {
var validate = true;
var unanswered = new Array();
// Loop through available sets
$('.option').each(function () {
// Question text
var question = $(this).prev();
// Validate
if (!$(this).find('input').is(':checked')) {
// Didn't validate ... dispaly alert or do something
unanswered.push(question.text());
question.css('color', 'red'); // Highlight unanswered question
validate = false;
}
});
if (unanswered.length > 0) {
msg = "Please answer the following questions:\n" + unanswered.join('\n');
alert(msg);
}
return validate;
});
I'm getting alert as a blank, only one line is written please answer following questions but no questions number inside
Just put your questions in a tag ( I have put it in span tag ) with an unique id and it should work with your code.
$(document).on('submit', 'form', function () {
var validate = true;
var unanswered = new Array();
// Loop through available sets
$('.option').each(function () {
// Question text
var question = $(this).prev();
// Validate
if (!$(this).find('input').is(':checked')) {
// Didn't validate ... dispaly alert or do something
//alert(JSON.stringify($(this).siblings()));
unanswered.push(question.text());
question.css('color', 'red'); // Highlight unanswered question
validate = false;
}
});
if (unanswered.length > 0) {
//alert(unanswered);
msg = "Please answer the following questions:\n" + unanswered.join('\n');
alert(msg);
}
return validate;
});
<body>
<form id='form' action='#' method='post'>
<span id='q1'>question 1</span>
<ul class="option">
<li> <input type="radio" name="question1" id="sd1" value="1">Strongly Disagree</li>
<li> <input type="radio" name="question1" id="d1" value="2">Disagree</li>
<input type="radio" name="question1" id="n1" value="3">Neither Agree Nor Dis<li>agree</li>
<li> <input type="radio" name="question1" id="a1" value="4">Agree</li>
<li> <input type="radio" name="question1" id="sa1" value="5">Strongly Agree
</li></ul>
<br/><br/>
<span id='q2'>question 2</span>
<ul class="option">
<li> <input type="radio" name="question2" id="sd2" value="1">Strongly Disagree</li>
<li> <input type="radio" name="question2" id="d2" value="2">Disagree</li>
<li> <input type="radio" name="question2" id="n2" value="3">Neither Agree Nor Disagree</li>
<li> <input type="radio" name="question2" id="a2" value="4">Agree</li>
<li> <input type="radio" name="question2" id="sa2" value="5">Strongly Agree
</li></ul>
<input type='submit' value='submit'>
</form>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
</body>
I have a list of questions in HTML. Each question will have 4 radio buttons for the answers, and the user will select the appropriate answer. Each radio button has an assigned value. At the end, I would like to show in HTML, the user's score once the questions have all been answered.
It's fairly straight forward, but I am having issues iterating through the questions and returning a summing the total value for their score.
Any suggestions on the iterating jQuery loops would be helpful.
<div>
<p class="question">1. Question:</p>
<ul id="answers1">
<input type="radio" name="q1" value="15" id="q1a"><label for="q1a"> Answer 1</label><br/>
<input type="radio" name="q1" value="10" id="q1b"><label for="q1b"> Answer 2</label><br/>
<input type="radio" name="q1" value="5" id="q1c"><label for="q1c"> Answer 3</label><br/>
<input type="radio" name="q1" value="1" id="q1d"><label for="q1d"> Answer 4</label><br/>
</ul>
<p class="question">2. Question</p>
<ul id="answers2">
<input type="radio" name="q2" value="15" id="q2a"><label for="q2a"> Answer 1</label><br/>
<input type="radio" name="q2" value="10" id="q2b"><label for="q2b"> Answer 2</label><br/>
<input type="radio" name="q2" value="5" id="q2c"><label for="q2c"> Answer 3</label><br/>
<input type="radio" name="q2" value="1" id="q2d"><label for="q2d"> Answer 4</label><br/>
</ul>
<p class="question">3. Question</p>
<ul id="answers3">
<input type="radio" name="q3" value="1" id="q3a"><label for="q3a">Answer 1</label><br/>
<input type="radio" name="q3" value="5" id="q3b"><label for="q3b">Answer 2</label><br/>
<input type="radio" name="q3" value="10" id="q3c"><label for="q3c">Answer 3</label><br/>
<input type="radio" name="q3" value="15" id="q3d"><label for="q3d">Answer 4</label><br/>
</ul>
<div id="sum" >Print Score from Questions Here</div>
</div>
You can get total score usong this.
var score=0;
$("input[type='radio']:checked").each(function () {
score += $(this).val();
});
$('#sum').text(score);
I am using a tutorial that had me create an html form with an external javascript. When I click on a radio button, I'm supposed to get an alert with the value of the answer. Instead I get 'undefined' no matter which answer I click.
I put this on JSBin. https://jsbin.com/docavo/edit?html,js,output
In one attempt to solve I just grabbed the project files provided by the tutor and put that code into the JSBin fields, and got the same result.
So the code (and tutorial ) are wrong, but it works in the tutorial.
What to do?
The form's ability to post is hindered by the sandboxed iframe for this snippet. If you want to see that function correctly, you can run it on your own site. The quiz works.
What the commenters, pTi and n6 said I applied to this snippet.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Multiple Choice Quiz</title>
<link href="http://glpjt.s3.amazonaws.com/_css/01.css" rel="stylesheet" />
<style>
iframe {
border-radius: 8px;
margin-top: 20px;
}
.ui {
border-radius: 8px;
max-width: 300px;
border: 2px ridge #8cf;
padding: 10px;
}
legend,
figcaption {
color: #8cf;
font-size: 1.35rem;
font-variant: small-caps;
}
#php {
background: #fff;
}
dt {
margin-top: 12px;
}
</style>
</head>
<body>
<section id="ii">
<form id="quizForm" name="quizForm" action="https://httpbin.org/post" target="php" method="post" onsubmit="submitAnswers();">
<dl>
<dt>1. In which HTML element do we put in JavaScript code?</dt>
<dd>
<input type="radio" name="q0" value="a" id="q0a" />a. <js></dd>
<dd>
<input type="radio" name="q0" value="b" id="q0b" class="correct" />b. <script></dd>
<dd>
<input type="radio" name="q0" value="c" id="q0c" />c. <body></dd>
<dd>
<input type="radio" name="q0" value="d" id="q0d" />d. <link></dd>
<dt>2. Which HTML attribute is used to reference an external JavaScript file?</dt>
<dd>
<input type="radio" name="q1" value="a" id="q1a" class="correct" />a. src</dd>
<dd>
<input type="radio" name="q1" value="b" id="q1b" />b. rel</dd>
<dd>
<input type="radio" name="q1" value="c" id="q1c" />c. type</dd>
<dd>
<input type="radio" name="q1" value="d" id="q1d" />d. href</dd>
<dt>3. How would you write "Hello" in an alert box?</dt>
<dd>
<input type="radio" name="q2" value="a" id="q2a" />a. msg("Hello");</dd>
<dd>
<input type="radio" name="q2" value="b" id="q2b" />b. alertBox("Hello");</dd>
<dd>
<input type="radio" name="q2" value="c" id="q2c" />c. document.write("Hello");</dd>
<dd>
<input type="radio" name="q2" value="d" id="q2d" class="correct" />d. alert("Hello");</dd>
<dt>4. JavaScript is directly related to the "Java" programming language</dt>
<dd>
<input type="radio" name="q3" value="a" id="q3a" />a. True</dd>
<dd>
<input type="radio" name="q3" value="b" id="q3b" class="correct" />b. False</dd>
<dt>5. A variable in JavaScript must start with which special character</dt>
<dd>
<input type="radio" name="q4" value="a" id="q4a" />a. #</dd>
<dd>
<input type="radio" name="q4" value="b" id="q4b" />b. $</dd>
<dd>
<input type="radio" name="q4" value="c" id="q4c" />c. #</dd>
<dd>
<input type="radio" name="q4" value="d" id="q4d" class="correct" />d. No Special Character</dd>
</dl>
<fieldset class="ui">
<legend>Post Data to Server</legend>
<input id="btn" type="submit" value="Submit" />
<label for="results"> Results:
<output for="quizForm" id="results">0</output><span id="outOf"></span>
</label>
</fieldset>
</form>
</section>
<figure>
<figcaption>Data Received by Server</figcaption>
<iframe id="php" name="php" src="http://examples.funwebdev.com/process.php" frameborder="2" scrolling="yes"></iframe>
</figure>
<footer> </footer>
<script>
function submitAnswers() {
var res = document.getElementById('results');
var keys = document.querySelectorAll('.correct');
var total = keys.length;
var score = 0;
var outOf = document.getElementById('outOf');
var keyArray = Array.prototype.slice.call(keys);
for (var k = 0; k < total; k++) {
var keyVal = keyArray[k].value;
var ansVal = document.forms['quizForm']['q' + k].value;
if (ansVal == keyVal) {
score++;
} else {
continue;
}
}
console.log('Score: ' + score);
outOf.innerHTML = ' / ' + total;
return res.value = score;
}
</script>
</body>
</html>
I made a test and I'm trying to get the values associated with each answer so i can give the user a score based on those values. Right now the code gives me double the answers worth. Right now there are 7 questions and each time the user clicks the radio button with the right answer it should be worth 1 point. At the end when I submit test it seems as if all the values were doubled(getting a 200% when i only got 100%). Any help is appreciated.
Here is my test:
<ol>
<li>What are the three main areas of the Standard User Interface?
<ul type="none">
<li><input type="radio" name="q1" value="0" />Header, Banner, Frame, Application Window</li>
<li><input type="radio" name="q1" value="0" /> Content Frame, Homepage, Form </li>
<li><input type="radio" name="q1" value="1" onchange="checkAnswer()"/> Application Navigator, Banner Frame, Content Frame </li>
<li><input type="radio" name="q1" value="0" /> Larry, Moe, and Curly</li>
</ul>
</li>
<li>In the User interface, what is the gray toolbar called which allows you to add bookmarks?
<ul type="none">
<li><input type="radio" name="q2" value="0" /> Gauge</li>
<li><input type="radio" name="q2" value="1" onchange="checkAnswer()"/> Edge</li>
<li><input type="radio" name="q2" value="0" /> Remedy</li>
<li><input type="radio" name="q2" value="0" /> Banner</li>
</ul>
</li>
<li>What can be captured in an update set?
<ul type="none">
<li><input type="radio" name="q3" value="0" /> Modified CI Rules</li>
<li><input type="radio" name="q3" value="1" onchange="checkAnswer()"/> Business Rules</li>
<li><input type="radio" name="q3" value="0" /> Scheduled Jobs</li>
<li><input type="radio" name="q3" value="0" /> None of these</li>
</ul>
</li>
<li>What should you always do before you commit an update set?
<ul type="none">
<li><input type="radio" name="q4" value="1" onchange="checkAnswer()" /> Preview</li>
<li><input type="radio" name="q4" value="0" /> Merge</li>
<li><input type="radio" name="q4" value="0" /> Ignore</li>
<li><input type="radio" name="q4" value="0" /> All of these</li>
</ul>
</li>
<li>Which of the following is a Business Rule best pratice?
<ul type="none">
<li><input type="radio" name="q5" value="1" onchange="checkAnswer()" /> Make business rules small and specific</li>
<li><input type="radio" name="q5" value="0" /> Use of conditions is not necessary</li>
<li><input type="radio" name="q5" value="0" /> Global business rules should be used</li>
<li><input type="radio" name="q5" value="0" /> None of these</li>
</ul>
</li>
<li>Which of the following is a Client Script best practice?
<ul type="none">
<li><input type="radio" name="q6" value="0" /> Use hard coded data</li>
<li><input type="radio" name="q6" value="0" /> Maximize server lookup</li>
<li><input type="radio" name="q6" value="1" onchange="checkAnswer()" /> Do not use g_form.getReference()</li>
<li><input type="radio" name="q6" value="0" /> All of these</li>
</ul>
</li>
<li>Which of the following are debugging features?
<ul type="none">
<li><input type="radio" name="q7" value="0" /> Debug Business Rule</li>
<li><input type="radio" name="q7" value="0" /> Javascript</li
<li><input type="radio" name="q7" value="1" onchange="checkAnswer()" /> Debug Business Rule and Javascript</li>
<li><input type="radio" name="q7" value="0" /> There is none</li>
</ul>
</li>
</ol>
<button onclick="finishTest()"> Submit Test </button>
Here is my javascript:
var question=document.getElementsByTagName("input");
var grade;
var score = 0;
var totalQuestions = 7;
function checkAnswer(){
for(var questionNum = 0; questionNum<totalQuestions; questionNum++){
var answer = question[questionNum].value;
if(answer=="1"){
score+=1;
}else{
score+=0;
}
grade = "%" + (score/totalQuestions)*100;
}
}
function finishTest(){
alert(" You scored a " +grade);
}
I used this function instead
function finishTest()
{
var score = 0;
var maxQues = 7;
for(var questionNum = 1; questionNum<=maxQues; questionNum++){
var radios = document.getElementsByName('q'+questionNum);
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked && radios[i].value=="1") score++;
}
}
score = parseFloat(score*100/maxQues).toFixed(1);
alert("You scored "+score+"%");
}
Working Fiddle