I'm trying to create a Quiz for a Spanish class. I have little experience with JavaScript, but am fairly proficient with html and CSS. I have a question and followed by three radio buttons with answers. There are two incorrect answers and a correct answer. I have 45 questions total.
<form name="quiz" method="post" name="buttons" id="form" onsubmit="return totalVal()">
<li><div class="question">¿Quién detestan la nueva casa?</div></li>
<input id="answer" type="radio" name="group1" value="wrong"> Josh<br>
<input id="answer" type="radio" name="group1" value="wrong"> Amanda<br>
<input id="answer" type="radio" name="group1" value="correct"> Josh y Amanda<hr>
<li><div class="question">¿Quién es señor Dawes?</div></li>
<input id="answer" type="radio" name="group2" value="wrong">Un familia amigo<br>
<input id="answer" type="radio" name="group2" value="wrong">Un gato<br>
<input id="answer" type="radio" name="group2" value="correct">Un amable joven de la agencia de bienes raíces<hr>
<li><div class="question">¿Quién qué sus buscan?</div></li>
<input id="answer" type="radio" name="group3" value="wrong">Josh<br>
<input id="answer" type="radio" name="group3" value="wrong"> Petey<br>
<input id="answer" type="radio" name="group3" value="correct" >Josh y Petey<hr>
<button class="submit" onclick="showTotalvalue();" type="submit">Submit</button></div>
I want to use some basic Javascript to count all the "correct" radio button values and output to a new page or alert box that displays after the user clicks submit.
I found this in my research. In my googling, I haven't been able to find a snippet of code that counts the "correct" values. The link above is the closest I've gotten. I attached the JavaScript that I changed to fit my situation from the suggestion on the other post.
totalVal = 0;
// calculate the total number of corrects clicked
for (y = 0; y = incorrectOfQuestion; y++) {
var questionNo = document.getElementsByName("questions" + y);
for (i = 0; i < questionNo.length; i++) {
if (document.myform.questions[i].checked == true) {
totalVal = totalVal + parseInt(document.myform.questions[i].value, 45);
}
}
}
Any assistance is greatly appreciated as I am in a time crunch! Thank you!
This should be the code you require to get it working with an alert box:
function handleClick()
{
var amountCorrect = 0;
for(var i = 1; i <= 45; i++) {
var radios = document.getElementsByName('group'+i);
for(var j = 0; j < radios.length; j++) {
var radio = radios[j];
if(radio.value == "correct" && radio.checked) {
amountCorrect++;
}
}
}
alert("Correct Responses: " + amountCorrect);
}
<form name="quiz" method="post" name="buttons" id="quiz" onsubmit="return false">
<li><div class="question">¿Quién detestan la nueva casa?</div></li>
<input id="answer" type="radio" name="group1" value="wrong"> Josh<br>
<input id="answer" type="radio" name="group1" value="wrong"> Amanda<br>
<input id="answer" type="radio" name="group1" value="correct"> Josh y Amanda<hr>
<li><div class="question">¿Quién es señor Dawes?</div></li>
<input id="answer" type="radio" name="group2" value="wrong">Un familia amigo<br>
<input id="answer" type="radio" name="group2" value="wrong">Un gato<br>
<input id="answer" type="radio" name="group2" value="correct">Un amable joven de la agencia de bienes raíces<hr>
<li><div class="question">¿Quién qué sus buscan?</div></li>
<input id="answer" type="radio" name="group3" value="wrong">Josh<br>
<input id="answer" type="radio" name="group3" value="wrong"> Petey<br>
<input id="answer" type="radio" name="group3" value="correct" >Josh y Petey<hr>
<button class="submit" onclick="return handleClick();" type="submit">Submit</button>
</form>
#pimvdb had used the === operator when checking for the "correct" string which does not allow type conversion and was therefore failing. He also used getElementsByClassName but the elements do not have a class applied to them so this was incorrect.
The working version can be found in the fiddle below. As you can see the onsubmit of the form has been set to "return false" to stop the form from posting.
http://jsfiddle.net/g45nG/1/
You can loop over each radio group, then loop over each radio button to check whether the correct one is checked.
var amountCorrect = 0;
for(var i = 1; i <= 45; i++) {
var radios = document.getElementsByName("group" + i);
for(var j = 0; j < radios.length; j++) {
var radio = radios[j];
if(radio.value === "correct" && radio.checked) {
amountCorrect++;
}
}
}
Related
I did it as you wanted and it still doesn't work as it should, if I don't check anything in the checkbox and give it an "evaluate test" so it will write me 1 point anyway, which is wrong. Some ideas?
function check(){
var question1 = document.querySelector('input[name="question1"]:checked');
var question2 = document.querySelectorAll('input[value="question2"]:checked', 'input[value="question2"]:checked');
var correct = 0;
if (question1 !=null && question1.value == " Červená, Zelená, Modrá") {
correct++;
}
if (question4 !=null &&question4.value == "Rastrová grafika","Vektorová grafika"){
correct++;
}
document.getElementById("number_correct").innerHTML = "Máš " + correct + " otázky/otázek správně.";
}
<form class="quiz">
<p style="font-weight: 900">V RGB modelu se jedná o jaké barvy?</p>
<input type="radio" class='question1' name="question1" value=" Červená, Zelená, Modrá"> Červená, Zelená, Modrá<br>
<input type="radio" class='question1' name="question1" value=" Červená, Zelená, Žlutá"> Červená, Zelená, Žlutá<br>
<input type="radio" class='question1' name="question1" value=" Černá, Fialová, Modrá"> Červená, Fialová, Modrá<br>
</form>
<form class="quiz">
<p style="font-weight: 900">Způsoby jakým počítače ukládají a zpracovávají obrazové informace se nazývají? (Vyber dvě možnosti)</p>
<input type="checkbox" class='question2' name="question4" value=" 3D grafika"> 3D grafika<br>
<input type="checkbox" class='question2' name="question4" value=" Vektorová grafika"> Vektorová grafika<br>
<input type="checkbox" class='question2' name="question4" value=" Fotografika"> Fotografika<br>
<input type="checkbox" class='question2' name="question4" value=" Rastrová grafika"> Rastrová grafika<br>
</form>
<br>
<div id="number_correct"></div>
question2 needs to be the result of a call to querySelectorAll, not just querySelector. It will then be a list of all the checked elements (querySelector only returns the first matched element, no matter how many match the selector.
You would need to loop the list and see what it contains. You need to verify that only two boxes were checked, and that they were the correct ones.
Also in your code, the question4 variable isn't defined, and input[value="question2"]:checked will never match anything - there's no checkbox with that value, and looking for the value makes no sense anyway. Also your question2 checkboxes randomly had "question4" as their name. I've corrected those issues and a couple of other minor things.
Something like this will work better:
function check() {
var question1 = document.querySelector('input[name="question1"]:checked');
var question2 = document.querySelectorAll('input[name="question2"]:checked');
var correct = 0;
if (question1 != null && question1.value == "Červená, Zelená, Modrá") {
correct++;
}
var q2answers = ["Rastrová grafika", "Vektorová grafika"];
var correctQ2NumAnswers = (q2answers.length == question2.length);
var correctQ2AnswersCount = 0;
question2.forEach(function(el) {
if (q2answers.includes(el.value)) correctQ2AnswersCount++;;
});
if (correctQ2NumAnswers == true && correctQ2AnswersCount == q2answers.length) correct++;
document.getElementById("number_correct").innerHTML = "Máš " + correct + " otázky/otázek správně.";
}
document.querySelector("#check").addEventListener("click", check);
<form class="quiz">
<p style="font-weight: 900">V RGB modelu se jedná o jaké barvy?</p>
<input type="radio" class='question1' name="question1" value="Červená, Zelená, Modrá"> Červená, Zelená, Modrá<br>
<input type="radio" class='question1' name="question1" value="Červená, Zelená, Žlutá"> Červená, Zelená, Žlutá<br>
<input type="radio" class='question1' name="question1" value="Černá, Fialová, Modrá"> Červená, Fialová, Modrá<br>
</form>
<form class="quiz">
<p style="font-weight: 900">Způsoby jakým počítače ukládají a zpracovávají obrazové informace se nazývají? (Vyber dvě možnosti)</p>
<input type="checkbox" class='question2' name="question2" value="3D grafika"> 3D grafika<br>
<input type="checkbox" class='question2' name="question2" value="Vektorová grafika"> Vektorová grafika<br>
<input type="checkbox" class='question2' name="question2" value="Fotografika"> Fotografika<br>
<input type="checkbox" class='question2' name="question2" value="Rastrová grafika"> Rastrová grafika<br>
</form>
<br>
<div id="number_correct"></div>
<button type="button" id="check">
Check Answers
</button>
i made some code recently but im wondering how to make the quiz choose 3 questions out of 6 instead of displaying 6 straight away. Help would be appreciated. I want the quiz to choose 3 questions at random, then if its reloaded have a chance to choose another 3 questions, out of a total pool of 6.
<script language="JavaScript">
var numQues = 6;
var numChoi = 3;
var answers = new Array(6);
answers[0] = "16";
answers[1] = "8";
answers[2] = "The Walking Dead";
answers[3] = "Batman v Superman";
answers[4] = "Tupac";
answers[5] = "#ATAME2016";
function getScore(form) {
var score = 0;
var currElt;
var currSelection;
for (i=0; i<numQues; i++) {
currElt = i*numChoi;
for (j=0; j<numChoi; j++) {
currSelection = form.elements[currElt + j];
if (currSelection.checked) {
if (currSelection.value == answers[i]) {
score++;
break;
}
}
}
}
score = Math.round(score/numQues*100);
form.percentage.value = score + "%";
var correctAnswers = "";
for (i=1; i<=numQues; i++) {
correctAnswers += i + ". " + answers[i-1] + "\r\n";
}
form.solutions.value = correctAnswers;
}
</script>
</head>
<body>
<form name="quiz">
1. How many movie trailers are on the movie page?<br>
<input type="checkbox" name="question1" value="10">10<br>
<input type="checkbox" name="question1" value="14">14<br>
<input type="checkbox" name="question1" value="16">16<br>
<p>
2. How many pages are on this website?<br>
<input type="checkbox" name="q2" value="8">8<br>
<input type="checkbox" name="q2" value="6">6<br>
<input type="checkbox" name="q2" value="7">7<br>
<p>
3. What's the most popular show this week?<br>
<input type="checkbox" name="q3" value="The Walking Dead">The Walking Dead<br>
<input type="checkbox" name="q3" value="Mandem on the wall">Mandem on the wall<br>
<input type="checkbox" name="q3" value="Cotchin with Ksara">Cotchin with Ksara<br>
<p>
4. What movie has made the most money this week in the box office?<br>
<input type="checkbox" name="q4" value="Ride along 2">Ride along 2<br>
<input type="checkbox" name="q4" value="Batman v Superman">Batman v Superman<br>
<input type="checkbox" name="q4" value="GasMan">GasMan<br>
<p>
5. Which star in the celebrity page is no longer alive?<br>
<input type="checkbox" name="q5" value="Tupac">Tupac<br>
<input type="checkbox" name="q5" value="50 Cent">50 Cent<br>
<input type="checkbox" name="q5" value="Bradley cooper">Bradley cooper<br>
<p>
6. What is our twitter account name (#)?<br>
<input type="checkbox" name="q6" value="#ATAME">#ATAME<br>
<input type="checkbox" name="q6" value="#ATAME2016">#ATAME2016<br>
<input type="checkbox" name="q6" value="#A2THETAME">#A2THETAME<br>
<p>
<input type="button" value="Get score" onClick="getScore(this.form)">
<input type="reset" value="Clear"><p>
Score = <input type=text size=15 name="percentage"><br>
Correct answers:<br>
<textarea name="solutions" wrap="virtual" rows="4" cols="40"></textarea>
</form>
</div>
You'll want to use a Math.random() function. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
A common example is found at: http://www.w3schools.com/jsref/jsref_random.asp
I'd try something like this, using jQuery:
// Hides all questions on page load.
$('.questions').hide();
// Randomly shows 3 questions.
for (var i=0; i<3; i++) {
var questionId = Math.floor((Math.random() * 6) + 1);
$('#question-' + questionId).show();
}
Then wrap your questions in wrapping <div> or <p> tags like this:
<div id="question-1" class="questions">
1. How many movie trailers are on the movie page?<br>
<input type="checkbox" name="question1" value="10">10<br>
<input type="checkbox" name="question1" value="14">14<br>
<input type="checkbox" name="question1" value="16">16<br>
</div>
Or this:
<p id="question-1" class="questions">
1. How many movie trailers are on the movie page?<br>
<input type="checkbox" name="question1" value="10">10<br>
<input type="checkbox" name="question1" value="14">14<br>
<input type="checkbox" name="question1" value="16">16<br>
</p>
I'm trying to create a 5 star radio picker.
This is the 1 of the radio buttons:
<input onclick="check(3)" type="radio" name="three" id="num_3_star" value="3">
After the method gets called and "3" is passed on this is my javascript function:
function check(stars)
{
for(i = 0 ; i < stars; i++)
{
document.getElementById("num_" + stars + "_star").checked = true;
}
}
When I run the code, it does not perform the checked to = true, though if remove the for loop, it works just fine.
Any ideas why the for loop is preventing from checking the radio boxes?
This is my entire code:
<script>
function check(stars)
{
for(i = 0 ; i < stars; i++)
{
document.getElementById("num_" + stars + "_star").checked = true;
}
}
</script>
<form>
<input onclick="check(1)" type="radio" name="one" id="num_1_star" value="1">
<input onclick="check(2)" type="radio" name="two" id="num_2_star" value="2">
<input onclick="check(3)" type="radio" name="three" id="num_3_star" value="3">
<input onclick="check(4)" type="radio" name="four" id="num_4_star" value="4">
<input onclick="check(5)" type="radio" name="five" id="num_5_star" value="5">
</form>
Thanks!
i had to be 1 initially as ids are starting from 1
Also reset all the checked status when click is initiated! Use i instead of stars in getElementById
Try this:
function check(stars) {
for (var j = 1; j <= 5; j++) {
document.getElementById("num_" + j + "_star").checked = false;
}
for (var i = 1; i <= stars; i++) {
document.getElementById("num_" + i + "_star").checked = true;
}
}
<input onclick="check(1)" type="radio" name="one" id="num_1_star" value="1">
<input onclick="check(2)" type="radio" name="two" id="num_2_star" value="2">
<input onclick="check(3)" type="radio" name="three" id="num_3_star" value="3">
<input onclick="check(4)" type="radio" name="four" id="num_4_star" value="4">
<input onclick="check(5)" type="radio" name="five" id="num_5_star" value="5">
Put var before the iteration variable i. You are creating a global variable.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have to some exercise for my javascript class.
The task I have to finish is creating a simple form where users are able to choose 1 option for each question, and once they have chosen selected options, the form will display their score.
<form id="form" name="form" method="post" action="">
<fieldset id="controls">
<p>Do you like chocolate?
<label>Yes a lot </label>
<input type="radio" name="choco" id="alot" value="Alot" checked="true">
<label>Not that much </label>
<input type="radio" name="choco" id="notMuch" value="NotMuch">
<label>No, but still I don't mind eating it sometimes </label>
<input type="radio" name="choco" id="noSometimes" value="NoSometimes">
<label>No, I hate it </label>
<input type="radio" name="choco" id="hate" value="Hate">
</p>
<p>Do you prefer chocolate cake or carrot cake?
<label>chocolate </label>
<input type="radio" name="cake" id="chocolate" value="Chocolate" checked="true">
<label>Carrot </label>
<input type="radio" name="cake" id="carrot" value="Carrot">
<label>Both</label>
<input type="radio" name="cake" id="both" value="Both">
<label>None </label>
<input type="radio" name="cake" id="none" value="None">
</p>
<p>
<input type="submit" name="Calculate" id="calculate" value="Calculate" />
</p>
So I thought I will create a very short form that asks the user 2 question, to find out how much the person likes or dislikes chocolate.
And for the calculation I did the following coding:
var numericalValues = new Array();
numericalValues["Alot"]= 4;
numericalValues["NotMuch"]= 2;
numericalValues["NoSometimes"]= 3;
numericalValues["Hate"]= 0;
numericalValues["Chocolate"]= 4;
numericalValues["Carrot"]= 0;
numericalValues["Both"]= 2;
numericalValues["None"]= 0;
function getScoreChoco(){
var scoreChoco = 0;
var form = document.forms["form"];
var choco = form.elements["choco"];
for(var i=0; i<choco.length; i++){
if(choco[i].checked){
totalScore = numericalValues[choco[i].value];
break;
}
}
return scoreChoco;
}
function getScoreCake(){
var scoreCake = 0;
var form = document.forms["form"];
var cake = form.elements["diabetic1"];
for(var i=0; i<cake.length; i++){
if(cake[i].checked){
totalScore = numericalValues[cake[i].value];
break;
}
}
return scoreCake;
}
function getTotal(){
var totalScore = getScoreCake() + getScoreChoco()
document.getElementById('calculate').innerHTML =
"Your total score is: "+totalScore;
}
And the code is not working, help please :(
Here's my jsfiddle
I made few changes:
I assumed that you want to caluculate in javascript so i remove submit button from the form and change it with simple button with id 'calulate'
Then I bound onclick event for buton ('calculate') to getTotal function
in function getScoreChoco and getScoreCake i used you variable for returning score becouse you was using totalscore property of the window object not variable defined for return result
I paste javascript code becouse i have problem with jsFiddle
var numericalValues = new Array();
numericalValues["Alot"]= 4;
numericalValues["NotMuch"]= 2;
numericalValues["NoSometimes"]= 3;
numericalValues["Hate"]= 0;
numericalValues["Chocolate"]= 4;
numericalValues["Carrot"]= 0;
numericalValues["Both"]= 2;
numericalValues["None"]= 0;
function getScoreChoco()
{
var scoreChoco = 0;
var form = document.forms["form"];
var choco = form.elements["choco"];
for(var i=0; i<choco.length; i++)
{
if(choco[i].checked)
{
scoreChoco = numericalValues[choco[i].value];
break;
}
}
return scoreChoco;
};
function getScoreCake()
{
var scoreCake = 0;
var form = document.forms["form"];
var cake = form.elements["cake"];
for(var i=0; i<cake.length; i++)
{
if(cake[i].checked)
{
scoreCake = numericalValues[cake[i].value];
break;
}
}
return scoreCake;
};
function getTotal()
{
var totalScore = getScoreCake() + getScoreChoco();
document.getElementById('result').innerHTML =
"Your total score is: "+totalScore;
}
document.getElementById('calculate').onclick=getTotal;
EDIT And HTML Code
<form id="form" name="form">
<fieldset id="controls">
<p>Do you like chocolate?
<label>Yes a lot </label>
<input type="radio" name="choco" id="alot" value="Alot" checked="true">
<label>Not that much </label>
<input type="radio" name="choco" id="notMuch" value="NotMuch">
<label>No, but still I don't mind eating it sometimes </label>
<input type="radio" name="choco" id="noSometimes" value="NoSometimes">
<label>No, I hate it </label>
<input type="radio" name="choco" id="hate" value="Hate">
</p>
<p>Do you prefer chocolate cake or carrot cake?
<label>chocolate </label>
<input type="radio" name="cake" id="chocolate" value="Chocolate" checked="true">
<label>Carrot </label>
<input type="radio" name="cake" id="carrot" value="Carrot">
<label>Both</label>
<input type="radio" name="cake" id="both" value="Both">
<label>None </label>
<input type="radio" name="cake" id="none" value="None">
</p>
<p>
<input type="button" name="Calculate" id="calculate" value="Calculate" />
</p>
<p id="result"></p>
</form>
I am building an online store where the customer can select custom parts.
I'm quite new to javascript, but I've managed to create a radio button list, where the price is added from each section.
I would like a box to show all of the options selected, not just the sum total.
I've included the text with value and used parseInt. Is there an equivalent I can use to pull the text, not the number, from the value?
My code so far:
<head>
<script type="text/javascript">
function DisplayPrice(price){
var val1 = 0;
for( i = 0; i < document.form1.part.length; i++ ){
if( document.form1.part[i].checked == true ){
val1 = document.form1.part[i].value;
}
}
var val2 = 0;
for( i = 0; i < document.form2.part2.length; i++ ){
if( document.form2.part2[i].checked == true ){
val2 = document.form2.part2[i].value;
}
}
var val3 = 0;
for( i = 0; i < document.form3.part3.length; i++ ){
if( document.form3.part3[i].checked == true ){
val3 = document.form3.part3[i].value;
}
}
var sum=parseInt(val1) + parseInt(val2) + parseInt(val3);
document.getElementById('totalSum').value=sum;
}
</script>
</head>
<body>
<form name="form1" id="form1" runat="server">
<br>
<input id="rdo_1" type="radio" value="0 1.8ghz2xAMD" name="part" checked="checked" onclick="DisplayPrice(this.value);">1.8Ghz Dual Core AMD
<br>
<input id="rdo_2" type="radio" value="50 2ghz2xAMD" name="part" onclick="DisplayPrice(this.value);">2Ghz Dual Core AMD
<br>
</form>Choose your memory:<br />
<form name="form2" id="form2" runat="server">
<br>
<input id="rdo_1" type="radio" value="0 1333corsair1gb" name="part2" checked="checked" onclick="DisplayPrice(this.value);">1333 Corsair 1GB
<br>
<input id="rdo_2" type="radio" value="50 1333corsair2x1gb" name="part2" onclick="DisplayPrice(this.value);">1333 Corsair 2x1GB
<br>
</form>Choose your graphics card:<br />
<form name="form3" id="form3" runat="server">
<br />
<input id="rdo_1" type="radio" value="0 5830ATI1gb" name="part3" checked="checked" onclick="DisplayPrice(this.value);">1GB ATI 5830
<br />
<input id="rdo_2" type="radio" value="50 5850ATI1gb" name="part3" onclick="DisplayPrice(this.value);">1GB ATI 5850
<br />
<input id="rdo_3" type="radio" value="75 5870ATI1gb" name="part3" onclick="DisplayPrice(this.value);">1GB ATI 5870
<br />
</form>
</body>
Thanks in advance for any advice you can give.
The values seem to be consistently separated by a space. So you could use split() function to split the value in two parts, the first part containing the price and the second part containing the text.
var parts = value.split(" ");
var price = parseInt(parts[0]);
var text = parts[1];
That said, there are better/nicer ways to achieve the functional requirement, but that's up to you to as an learning exercise.