Sum of Radio button values printed to the user - javascript

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>

Related

How do I know if a user has selected an option in a form in html + javascript

I am trying to build a quiz with questions and options but I don't know how to add the options to the quiz. Also, I want to know if I selected the correct option and if the number of correct answers is shown at the end. Can someone help me build this?
I have tried adding options but I can't get the output needed.
<form align="center" id = "test">
Question 1: <input type="radio" name="radiogroup1" value="radio" id="radiogroup1"> Option 1
<input type="radio" name="radiogroup1" value="radio" id="radiogroup2"> Option 2 <br><be>
</form>
See if this helps you: (just an example to get the idea)
function submitAnswers() {
var total = 5;
var score = 0;
//Get user input
var q1 = document.forms["quizForm"]["q1"].value;
var q2 = document.forms["quizForm"]["q2"].value;
var q3 = document.forms["quizForm"]["q3"].value;
var q4 = document.forms["quizForm"]["q4"].value;
var q5 = document.forms["quizForm"]["q5"].value;
// Validation
for (var i = 1; i <= total; i++) {
if (eval('q' + i) == null || eval('q' + i) == '') {
alert("you missed question " + i);
return false;
}
}
//set correct answers
var answers = ["b", "d", "c", "a", "b"]
//check answers
for (var i = 1; i <= total; i++) {
if (eval('q' + i) == answers[i - 1]) {
score++;
}
}
alert('You scored ' + score + " out of " + total);
return false;
}
<div class="container">
<section>
<form name="quizForm" onsubmit="submitAnswers(); return false">
<h3>1. Question number one?</h3>
<input type="radio" name="q1" value="a" id="q1a"> a. answer11<br>
<input type="radio" name="q1" value="b" id="q1b"> b. answer12<br>
<input type="radio" name="q1" value="c" id="q1c"> c. answer13<br>
<input type="radio" name="q1" value="d" id="q1d"> d. answer14<br>
<h3>2. Question number two?</h3>
<input type="radio" name="q2" value="a" id="q2a"> a. answer21<br>
<input type="radio" name="q2" value="b" id="q2b"> b. answer22<br>
<input type="radio" name="q2" value="c" id="q2c"> c. answer23<br>
<input type="radio" name="q2" value="d" id="q2d"> d. answer24<br>
<h3>3. Question number three?</h3>
<input type="radio" name="q3" value="a" id="q3a"> a. answer31<br>
<input type="radio" name="q3" value="b" id="q3b"> b. answer32<br>
<input type="radio" name="q3" value="c" id="q3c"> c. answer33<br>
<input type="radio" name="q3" value="d" id="q3d"> d. answer34<br>
<h3>4. Question number four ?</h3>
<input type="radio" name="q4" value="a" id="q4a"> a. answer41<br>
<input type="radio" name="q4" value="b" id="q4b"> b. answer42<br>
<input type="radio" name="q4" value="c" id="q4c"> c. answer43<br>
<input type="radio" name="q4" value="d" id="q4d"> d. answer44<br>
<h3>5. Question number five ?</h3>
<input type="radio" name="q5" value="a" id="q5a">a. answer51<br>
<input type="radio" name="q5" value="b" id="q5b">b. answer52<br>
<br><br>
<input type="submit" value="Submit Answers">
</form>
</section>
</div>

multiple choice quiz with class correct and wrong

I created a multiple choice quiz, and it working perfectly, I mean get the total score written on the website, but I wish to change it to just giving an extra 'correct' or 'wrong' CSS class to the selected input radio buttons after the Submit button has been hit.
HTML:
<section class="quiz">
<div id="results"></div>
<form name="quizForm" onsubmit="return submitAnswer()">
<h4 class="quiz-title knowledge-content-list-item-subheader">Question 1</h4>
<p>Question 1</p>
<div class="quiz-answers">
<input data-answer type="radio" name="q1" value="a" id="q1a"><label for="q1a">Test 1</label><br>
<input data-answer type="radio" name="q1" value="b" id="q1b"><label for="q1b">Test 2</label><br>
<input data-answer type="radio" name="q1" value="c" id="q1c"><label for="q1c">Test 3</label><br>
</div>
<h4 class="quiz-title knowledge-content-list-item-subheader">Question 2</h4>
<p>Question 2</p>
<div class="quiz-answers">
<input data-answer type="radio" name="q2" value="a" id="q2a"><label for="q2a">Test 4</label><br>
<input data-answer type="radio" name="q2" value="b" id="q2b"><label for="q2b">Test 5</label><br>
<input data-answer type="radio" name="q2" value="c" id="q2c"><label for="q2c">Test 6</label><br>
</div>
<h4 class="quiz-title knowledge-content-list-item-subheader">Question 3</h4>
<p>Question 3</p>
<div class="quiz-answers">
<input data-answer type="radio" name="q3" value="a" id="q3a"><label for="q3a">Test 7</label><br>
<input data-answer type="radio" name="q3" value="b" id="q3b"><label for="q3b">Test 8</label><br>
<input data-answer type="radio" name="q3" value="c" id="q3c"><label for="q3c">Test 9</label><br>
</div>
<h4 class="quiz-title knowledge-content-list-item-subheader">Question 4</h4>
<p>Question 4</p>
<div class="quiz-answers">
<input data-answer type="radio" name="q4" value="a" id="q4a"><label for="q4a">Test 10</label><br>
<input data-answer type="radio" name="q4" value="b" id="q4b"><label for="q4b">Test 11</label><br>
<input data-answer type="radio" name="q4" value="c" id="q4c"><label for="q4c">Test 12</label><br>
</div>
<button id="btn-submit" class="btn btn-submit" type="submit" name="submit" value="submit">submit</button>
</form>
</div>
</section>
JavaScript:
function submitAnswer() {
var total = 4;
var score = 0;
// Get User Input
var q1 = document.forms["quizForm"]["q1"].value;
var q2 = document.forms["quizForm"]["q2"].value;
var q3 = document.forms["quizForm"]["q3"].value;
var q4 = document.forms["quizForm"]["q4"].value;
// Validation
for(i = 1; i <= total; i++){
if(eval('q'+i) == null || eval('q'+i) == ''){
alert('You missed question '+ i);
return false;
}
}
// Set Correct Answers
var answers = ["a", "b", "c", "a"];
// Check Answers
for(i = 1; i <= total; i++){
if(eval('q'+i) == answers[i - 1]){
score++;
}
}
// Display results
var results = document.getElementById('results');
results.innerHTML = '<h3>You scored <span>'+score+'</span> out of <span>'+total+'</span></h3>';
return false;
}
I would be really appreciated for any kind of help. Cheers
You can use classLis.add() for that. So in your JS you'd do
document.getElementById('q4a').classList.add('correct')
document.getElementById('q4b').classList.add('wrong')
document.getElementById('q4c').classList.add('wrong')

Multiple choice quiz - issue with radio buttons and functions

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")

Adding validations to see if radio button is not selected

I have the following code:
<li>1. question 1</li>
<li>
<input type="radio" name="question1" id="sd1" value="1">Strongly Disagree
<input type="radio" name="question1" id="d1" value="2">Disagree
<input type="radio" name="question1" id="n1" value="3">Neither Agree Nor Disagree
<input type="radio" name="question1" id="a1" value="4">Agree
<input type="radio" name="question1" id="sa1" value="5">Strongly Agree
</li>
<br/><br/>
<li>2. question 2 </li>
<li>
<input type="radio" name="question2" id="sd2" value="1">Strongly Disagree
<input type="radio" name="question2" id="d2" value="2">Disagree
<input type="radio" name="question2" id="n2" value="3">Neither Agree Nor Disagree
<input type="radio" name="question2" id="a2" value="4">Agree
<input type="radio" name="question2" id="sa2" value="5">Strongly Agree
</li>
<br/><br/>
<li>3. question 3</li>
<li>
<input type="radio" name="question3" id="sd3" value="1">Strongly Disagree
<input type="radio" name="question3" id="d3" value="2">Disagree
<input type="radio" name="question3" id="n3" value="3">Neither Agree Nor Disagree
<input type="radio" name="question3" id="a3" value="4">Agree
<input type="radio" name="question3" id="sa3" value="5">Strongly Agree
</li>
<br/><br/>
<input type="submit" value="Submit" name="Submit" id="Submit" />
I have such 30 questions. My requirement is that the user must answer all 30 questions.
How do I write javascript function such that a mesage is shown tot he user if he doesnt answer even one of the questions.
EDIT:
The problem with my javascript i sthis:
if ( (thisfrm.question3[0].checked == false) || (thisfrm.question3[1].checked == false) || (thisfrm.question3[2].checked == false) || (thisfrm.question3[3].checked == false) || (thisfrm.question3[4].checked == false))
{
alert('Please answer question 1');
return false;
}
the above code is repeated for every question without loop. i.e. it is written for each ques. but even when all ques are answered,it still displays Please answer question 1
This method makes use of jQuery and checks for unchecked radio buttons in a set of answers
HTML - add a class to your questions <li>
<li>1. question 1</li>
<li class="option">
<input type="radio" name="question1" id="sd1" value="1">Strongly Disagree
<input type="radio" name="question1" id="d1" value="2">Disagree
<input type="radio" name="question1" id="n1" value="3">Neither Agree Nor Disagree
<input type="radio" name="question1" id="a1" value="4">Agree
<input type="radio" name="question1" id="sa1" value="5">Strongly Agree
</li>
Javascript
// 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;
});
Example here http://fiddle.jshell.net/6jNpQ/2/
Below code is more simple and clean for even biggners
if (!$("input[name='html_elements']:checked").val()) {
alert('Nothing is checked!');
}
else {
alert('One of the radio buttons is checked!');
}
check out this below fiddle demo
Visit http://jsfiddle.net/creators_guru/DBd79/
Check this. Instead of validating each element you can use something like this
for(var i = 1 ; i <= 30 ; i++)
{
var radios = document.getElementsByName('question'+i);
var checked = false;
for (var j = 0, length = radios.length; j < length; j++)
{
if (radios[j].checked)
{
checked = true;
break;
}
}
if(!checked)
{
alert('Please answer question '+i);
break;
}
}
It looks like you're using only javascript. I recommend you adding jQuery to make writing javascript easier.
Anyway, only using javascript you can try this:
var questions = 30;
var answer_checked = false;
var one_not_checked = false;
for (var i = 1; i <= questions; i++) {
for (var j=0; j < document.getElementsByName('question'+i).length; j++) {
answer_checked = answer_checked || (thisfrm['question'+i][j].checked == true);
}
one_not_checked = one_not_checked || !answer_checked;
answer_checked = false;
}
if (one_not_checked) {
// your message to the user as one answer is not checked
}
Something like this?
if ($('input[type=radio]:checked').length <= 0) {
alert("No radio checked")
}
Or do it by name?
if ($('input[name=question1]:checked').length <= 0) {
alert("No radio checked")
}
You should use logical operator && for your condition
if ( (thisfrm.question3[0].checked == false) &&
(thisfrm.question3[1].checked == false) &&
(thisfrm.question3[2].checked == false) &&
(thisfrm.question3[3].checked == false) &&
(thisfrm.question3[4].checked == false) )
Here is the answer for your question. You can check this also.
Just using this code I have write it for your code. Please see below
HTML Code
<form method="POST" action="/echo/html/?html=;delay=3;">
<ul>
<li class="question">1) question 1</li>
<li class="answers">
<input type="radio" name="question1" id="11" value="1" />Strongly Disagree
<input type="radio" name="question1" id="12" value="2" />Disagree
<input type="radio" name="question1" id="13" value="3" />Neither Agree Nor Disagree
<input type="radio" name="question1" id="14" value="4" />Agree
<input type="radio" name="question1" id="15" value="5" />Strongly Agree
</li>
<li class="question">2) question 2</li>
<li class="answers">
<input type="radio" name="question2" id="21" value="1" />Strongly Disagree
<input type="radio" name="question2" id="22" value="2" />Disagree
<input type="radio" name="question2" id="23" value="3" />Neither Agree Nor Disagree
<input type="radio" name="question2" id="24" value="4" />Agree
<input type="radio" name="question2" id="25" value="5" />Strongly Agree
</li>
<li class="question">3) question 3</li>
<li class="answers">
<input type="radio" name="question3" id="31" value="1" />Strongly Disagree
<input type="radio" name="question3" id="32" value="2" />Disagree
<input type="radio" name="question3" id="33" value="3" />Neither Agree Nor Disagree
<input type="radio" name="question3" id="34" value="4" />Agree
<input type="radio" name="question3" id="35" value="5" />Strongly Agree
</li>
</ul>
<input type="submit" value="Submit" name="Submit" id="Submit" />
</form>
Javascript Code
$("form").submit(function () {
var allChecked = true;
$('li.answers').each(function () {
if (!$(':radio', this).is(':checked')) {
allChecked = false;
return false;
}
});
if (!allChecked) {
alert('Please fill the form completely...');
return false;
} else {
alert('You have filled the complete form.');
}
});
#by javascript
function validate(){
if (checkRadio("question1") && checkRadio("question2") && checkRadio("question3")){
return true;
}else{
alert("Please answer all Questions!");
return false;
}
}
function checkRadio(name){
var radio = document.forms.myForm[name];
for (var option in radio){
if(radio[option].checked){
return true;
}
}
return false;
}

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

Categories

Resources