Multiple choice quiz - issue with radio buttons and functions - javascript

I'm trying to create a multiple choice quiz using simple functions and radio buttons in the HTML form tags but it is only allowing me to check one radio button for the whole quiz instead of one per question.
Also, the submit button is not activating the function checkAll, I don't know if this is because I am trying to do something impossible or simple because I'm just missing something. Any help would be appreciated!
The code is below. . . I'm only new to JavasScript and html as well as StackOverflow, so sorry if I'm doing anything wrong with this question.
<head>
<script language="javascript">
var score=0;
function checkAll() {
function questioncheckOne(){
var correctAnswer = document.getElementById("a3")
if (correctAnswer.checked == true) {
score++;
alert("Correct, your score is now " +score)
}
else {
alert("Wrong, your score is now " +score)
}
};
function questioncheckTwo(){
var correctAnswer = document.getElementById("b2")
if (correctAnswer.checked == true) {
score++;
alert("Correct, your score is now " +score)
}
else {
alert("Wrong, your score is now " +score)
}
};
function questioncheckThree(){
var correctAnswer = document.getElementById("c4")
if (correctAnswer.checked == true) {
score++;
alert("Correct, your score is now " +score)
}
else {
alert("Wrong, your score is now " +score)
}
};
function questioncheckFour(){
var correctAnswer = document.getElementById("d3")
if (correctAnswer.checked == true) {
score++;
alert("Correct, your score is now " +score)
}
else {
alert("Wrong, your score is now " +score)
}
};
function questioncheckFive(){
var correctAnswer = document.getElementById("e3")
if (correctAnswer.checked == true) {
score++;
alert("Correct, your score is now " +score)
}
else {
alert("Wrong, your score is now " +score)
}
};
};
</script>
</head>
<body>
<form name ="Where in the world is...?">
<p>
Question1: Where in the world would you find the Spire?
</p>
<input type="radio" name="radio" id="a1" value="a1" /> Kerry. </input>
<input type="radio" name="radio" id="a2" value="a1" /> Galway. </input>
<input type="radio" name="radio" id="a3" value="a1" /> Dublin. </input>
<input type="radio" name="radio" id="a4" value="a1" /> Donegal. </input>
<p>
Question2: Where in the world would you find the Colosseum?
</p>
<input type="radio" name="radio" id="b1" value="a2" /> Taipei. </input>
<input type="radio" name="radio" id="b2" value="a2" /> Rome. </input>
<input type="radio" name="radio" id="b3" value="a2" /> Reykjavic. </input>
<input type="radio" name="radio" id="b4" value="a2" /> Brussels. </input>
<p>
Question3: Where in the world would you find the Taj Mahal?
</p>
<input type="radio" name="radio" id="c1" value="a3" /> London. </input>
<input type="radio" name="radio" id="c2" value="a3" /> Brisbane. </input>
<input type="radio" name="radio" id="c3" value="a3" /> Paris. </input>
<input type="radio" name="radio" id="c4" value="a3" /> Agra. </input>
<p>
Question4: Where in the world would you find the Parthenon?
</p>
<input type="radio" name="radio" id="d1" value="a4" /> Edinburgh. </input>
<input type="radio" name="radio" id="d2" value="a4" /> Oslo. </input>
<input type="radio" name="radio" id="d3" value="a4" /> Athens. </input>
<input type="radio" name="radio" id="d4" value="a4" /> Pyongyang. </input>
<p>
Question5: Where in the world would you find the Niagara Falls?
</p>
<input type="radio" name="radio" id="e1" value="a5" /> Hong Kong. </input>
<input type="radio" name="radio" id="e2" value="a5" /> Moscow. </input>
<input type="radio" name="radio" id="e3" value="a5" /> New York. </input>
<input type="radio" name="radio" id="e4" value="a5" /> Ottawa. </input>
<p>
<input type="button" name="submit" id="submit" value="submit" onclick="checkAll()" /> </input>
</p>
</form>
</body>
</html>

You will need to make the name attribute unique for each group of radio buttons. Currently, they are all named radio.
As for the checkAll function, the issue is that you are only defining the functions, never calling them. Within the checkAll function, actually call the other functions you've defined:
function checkAll() {
// existing function definitions here
questioncheckOne();
questioncheckTwo();
// etc
}

When you check the radio button, all other buttons with the same name are unchecked. In your case, you'll want each question's radios to have a separate name (right now, they are all "radio")

Related

Sum of Radio button values printed to the user

I'm very new to html.
I have a survey with two questions where the question choices are presented with radio buttons as this html code shows:
<form>
<p id="description">1. Question 1?</p>
<p>
<label><input type="radio" name="q1" value="5" /> Yes</label>
<label><input type="radio" name="q1" value="0" /> No</label>
</p>
<p id="description">2. Question 2?</p>
<p>
<label><input type="radio" name="q2" value="5" /> Yes</label>
<label><input type="radio" name="q2" value="0" /> No</label>
</p>
</form>
I want to print to the user the sum of his two selections.
So the output could be "You score is 10." if he answered yes to both questions etc.
How can I do this in the simplest way with the code being on the same page as the html code above? Is that possible?
var question1Answers = document.getElementsByName('q1');
var question2Answers = document.getElementsByName('q2');
var answer = 0;
question1Answers.forEach((e) => {
if (e.checked) {
answer += e.value;
break;
}
});
question2Answers.forEach((e) => {
if (e.checked) {
answer += e.value;
break;
}
});
console.log(answer);
please try this:
$("input[type='button']").click(function () {
var score = getChecklistItems();
alert("You score is : " + score);
});
function getChecklistItems() {
var total_score = 0
var result = $("input:radio:checked").get();
var checked_value = $.map(result, function (element) {
return $(element).attr("value");
});
for (i = 0; i < checked_value.length; i++) {
total_score += parseInt(checked_value[i])
}
return total_score
}
<form>
<p id="description">1. Question 1?</p>
<p>
<label><input type="radio" name="q1" value="5" /> Yes</label>
<label><input type="radio" name="q1" value="0" /> No</label>
</p>
<p id="description">2. Question 2?</p>
<p>
<label><input type="radio" name="q2" value="5" /> Yes</label>
<label><input type="radio" name="q2" value="0" /> No</label>
</p>
<p><input type="button" value="Submit"></p>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

PHP pass total value of radio button

How to count the total value of radio button within the same page and pass to another php file? The total will be count at this page and i can get the total from answer.php file.
<form action="answer.php" method="POST">
<input type="radio" name="q1" value="1" />Yes <br />
<input type="radio" name="q1" value="0" />No <br />
<input type="radio" name="q2" value="2" />Yes <br />
<input type="radio" name="q2" value="0" />No <br />
<input type="radio" name="q3" value="3" />Yes <br />
<input type="radio" name="q3" value="0" />No <br />
<input type="submit" value="submit" name="submit"/>
</form>
I suggest using an array to count your values.
<input type="radio" name="q[]" value="2" />
<input type="radio" name="q[]" value="3" />
<input type="radio" name="q[]" value="4" />
<input type="radio" name="q[]" value="5" />
This will result in $_POST['q'] being an array. You can now do:
echo "The total amount is ".array_sum($_POST['q']);
Using jQuery- it is easy, just iterate through the inputs and tally up the values. Note that I gave the form an Id so it can be targetted directly if you have other form. The total can be passed to your other page - either via AJAX or using a standard HTML form as a hidden field. Alternatively - since this is a form and you are already passing it to a PHP page - you could simply submit the form and tally up the $_POST variables on the other side.
$('#testForm input').on('change', function() {
var total=0;
$('input[type=radio]:checked', '#testForm').each(function(){
total += parseInt($(this).val());
})
alert(total)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="testForm" action="answer.php" method="POST">
<input type="radio" name="q1" value="1" />Yes <br />
<input type="radio" name="q1" value="0" />No <br />
<input type="radio" name="q2" value="2" />Yes <br />
<input type="radio" name="q2" value="0" />No <br />
<input type="radio" name="q3" value="3" />Yes <br />
<input type="radio" name="q3" value="0" />No <br />
<input type="submit" value="submit" name="submit"/>
</form>
Commented version for the OP:
$('#testForm input').on('change', function() {//triggers the function on any change in the form
var total=0;//initialises the total at 0 so that each round ottallying up resets before the tally
$('input[type=radio]:checked', '#testForm').each(function(){//selects each input in the #testForm that is checked
total += parseInt($(this).val());//adds the value of each checked radio button to the tally
})
alert(total); //alerts the final tally after all iterations
});
You don't need jquery for this. Add a class to your radio buttons so we can query them without risking getting other elements in the page, something like "my-radio"
This javascript will get you the sum:
function getRadioButtonsSum(radioClass) {
var radioBtns = document.querySelectorAll(radioClass);
var count = 0;
var i;
for (i = 0; i < radioBtns.length; i += 1) {
if (radioBtns[i].checked) {
count += +radioBtns[i].value;
}
}
return count;
}
getRadioButtonsSum('.my-radio');

Checking if a particular checkbox in a checkbox list is checked

I have a list of checkboxes:
<input name="choice" type="checkbox" id="choice1" value="A" />
<input name="choice" type="checkbox" id="choice2" value="B" />
<input name="choice" type="checkbox" id="choice3" value="C" />
<input name="choice" type="checkbox" id="choice4" value="D" />
Name is the same for all but id is different.
I need to check if a particular checkbox (for example the one with id=choice3 is checked.
Tried
if (this.choice.id === "choice3" && this.choice[2].checked) {
alert("checked!");
}
but it does not work - the alert is never reached
P.S. I need to use javascript not jquery
Thats how you do it without jQuery:
Suppose your form is like this:
<form id="myForm" action="test.php">
<input name="choice" type="checkbox" id="choice1" value="A"/>
<input name="choice" type="checkbox" id="choice2" value="B"/>
<input name="choice" type="checkbox" id="choice3" value="C"/>
<input name="choice" type="checkbox" id="choice4" value="D"/>
<input type="button" onclick="validate();" value="Submit form">
</form>
You can do the validation on submit this way:
function validate() {
if (document.getElementById('choice3').checked) {
alert("checked");
} else {
alert("You didn't check it! ");
}
}

Dynamic alerts with radio buttons

I have this HTML form below (radio buttons) which is having 3 questions with answers A, B and C.
<fieldset>
<legend>Question 1:</legend>
<label><input type="radio" value="1" name="first" />A</label> <br />
<label><input name="first" type="radio" value="2" />B</label> <br />
<label><input name="first" type="radio" value="3" />C</label> <br />
</fieldset>
<fieldset>
<legend>Question 2:</legend>
<label><input type="radio" value="1" name="second" />A</label> <br />
<label><input name="second" type="radio" value="2" />B</label> <br />
<label><input type="radio" value="3" name="second" />C</label> <br />
</fieldset>
<fieldset>
<legend>Question 3:</legend>
<label><input type="radio" value="1" name="third" />A</label> <br />
<label><input name="third" type="radio" value="2" />B</label> <br />
<label><input type="radio" value="3" name="third" />C</label> <br />
</fieldset>
<div id="display">Please answer all the questions</div>​
What I need here is a jQuery script to display 3 answers dynamically. The 3 answers should be like below:
Answer 1 (if 2 or more answers are A)
Answer 2 (if 2 or more answers are B)
Answer 3 (if 2 or more answers are C)
Nothing is displayed if the answers are A, B and C.
I'm not a jQuery pro but I just have the script (below) to check if the answers are completed or not. Can anyone help me with this?
$('input:radio').click(
function() {
var q = $('fieldset').length;
console.log('q: ' + q + '; checked: ' + $('input:radio:checked').length);
if ($('input:radio:checked').length == q){
$('#display').text('You\'ve completed all questions!');
}
else {
$('#display').text('You\'ve not yet finished...');
}
});​
Thanks in advance.
JSFiddle Demo - http://jsfiddle.net/BhanuChawla/KSd3M/
Here is one possible solution:
var answers = {
"1": "Answer 1",
"2": "Answer 2",
"3": "Answer 3"
};
$("input[type='radio']").on("click", function() {
var vals = $("fieldset input:checked").map(function() {
return this.value;
}).get().sort();
for (var i = 0; i < vals.length; i++) {
if (vals[i] == (vals[i + 1] || null)) {
$("#display").text(answers[vals[i]]);
break;
}
}
});​
DEMO: http://jsfiddle.net/mLnWP/
Here i have done complete bins for above issue. you can check demo link too.
Demo: http://codebins.com/bin/4ldqp74
HTML
<fieldset>
<legend>
Question 1:
</legend>
<label>
<input type="radio" value="1" name="first" />
A
</label>
<label>
<input name="first" type="radio" value="2" />
B
</label>
<label>
<input name="first" type="radio" value="3" />
C
</label>
</fieldset>
<fieldset>
<legend>
Question 2:
</legend>
<label>
<input type="radio" value="1" name="second" />
A
</label>
<label>
<input name="second" type="radio" value="2" />
B
</label>
<label>
<input type="radio" value="3" name="second" />
C
</label>
</fieldset>
<fieldset>
<legend>
Question 3:
</legend>
<label>
<input type="radio" value="1" name="third" />
A
</label>
<label>
<input name="third" type="radio" value="2" />
B
</label>
<label>
<input type="radio" value="3" name="third" />
C
</label>
</fieldset>
<div id="display">
Please answer all the questions
</div>
JQuery
$(function() {
var answers = Array();
$("input:radio").click(function() {
var index = 0;
if ($(this).is(":checked")) {
index = $(this).closest("fieldset").index();
answers[index] = $(this).val().trim();
}
for (var i = 0; i < answers.length; i++) {
if ($("input:radio[value=" + answers[i] + "]:checked").length > 1) {
$("#display").text("Max Answers Selected:" + answers[i]);
break;
} else if ($("input:radio:checked").length >= 3) {
$("#display").text("All have different Answers..!");
}
}
});
});
CSS
label{
float:left;
margin-left:10px;
font-size:14px;
}
#display{
margin-top:10px;
border:1px solid #335599;
padding:5px;
font-size:14px;
background:#a4a1df;
}
Demo: http://codebins.com/bin/4ldqp74

JavaScript radio buttons

I have a few radio buttons, and when I select one of them, I also have to check another one.
For example, if I select yes on a radio button, another radio button must be automatically checked with no.
I tried a few scripts but don't seem to work.
Does anyone know a solution? I'm new in JS.
Thanks in advance!
             > Live Demo <              
<!--HTML-->
<input type="radio" name="group_1" value="yes" id="r1">Yes<br>
<input type="radio" name="group_1" value="no" id="r2">No<br>
<br>
<input type="radio" name="group_2" value="yes" id="r3">Yes<br>
<input type="radio" name="group_2" value="no" id="r4">No<br>​
//Script
$("input[name='group_1']").click(function(){
if(this.value=="yes"){
$("input#r4").attr("checked",true);
}else{
$("input#r3").attr("checked",true);
}
});
$("input[name='group_2']").click(function(){
if(this.value=="yes"){
$("input#r2").attr("checked",true);
}else{
$("input#r1").attr("checked",true);
}
});​
I'm not very certain on what you are trying to achieve but by using the "name" attribute this automatically happens...when you check one radio...the others with the same name get set to unchecked.
<input type="radio" name="someoption" value="0" />0
<input type="radio" name="someoption" value="1" />1
<input type="radio" name="someoption" value="2" />2
checking any one of the above will cause the other 2 to be unchecked
unless do you may be mean checkboxes or multiple option sets ?
javascript:
$('#myradio1').bind('change', function () {
$('#myradio3').attr('checked', 'checked');
});
html
<input type="radio" name="cols1" value="1" id="myradio1" />
<input type="radio" name="cols1" value="2" id="myradio2" />
<input type="radio" name="cols2" value="1" id="myradio3" />
<input type="radio" name="cols2" value="2" id="myradio4" />
see working example at http://jsfiddle.net/9jXbv/
For HTML markup like below:
<div>
<input type="radio" name="one" value="yes"> yes
<input type="radio" name="one" value="no"> no
</div>
<div>
<input type="radio" name="two" value="yes"> yes
<input type="radio" name="two" value="no"> no
</div>
you can use this JavaScript code:
$(":radio").on("change", function() {
var that = this;
$(":radio").filter(function() {
return this.value == "no" && this.name != that.name;
}).prop("checked", true);
});​
DEMO: http://jsfiddle.net/nKLMX/
With jquery:
​$("#radio1").change(function() {
$("#radio2").removeAttr("checked");
});​​​
http://jsfiddle.net/
I've mocked up a pure JS solution to this ( No libraries )
<input type="radio" name="g1" value="1" />Yes
<br />
<input type="radio" name="g1" value="0" />No
<br /><br />
<input type="radio" name="g2" value="1" />Yes
<br />
<input type="radio" name="g2" value="0" />No
<script type="text/javascript">
var g1 = document.getElementsByName('g1'); // store g1 elements
var g2 = document.getElementsByName('g2'); // store g2 elements
// handle click functionality
function radio_checked_event(obj, f) {
if(obj.addEventListener) {
obj.addEventListener('click', f, false);
} else if(obj.attachEvent) {
obj.attachEvent('onclick', f);
}
}
// when you click on g1 yes
radio_checked_event(g1[0], function() {
//set g1 no to checked
g2[1].setAttribute('checked', 'checked');
});
</script>

Categories

Resources