Java script radio buttons - javascript

I'm using Javascript and radio buttons for the first time.
I need to know how to assign the script to each radio button that is selected? there seem to be a few ways of doing this and its just getting confusing!
Each question has 4 radio buttons to select from and I need to gather the answers at the end!
Any help appreciated

Just add an event listener to the radio buttons and maintain a mapping where you could store all your answers to.
let answers = {}
$('input[type=radio]').on('click', function (event) {
let question = event.currentTarget.name
let answer = event.currentTarget.value
answers[question] = answer
document.getElementById('result').innerHTML = JSON.stringify(answers, null, 2)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="question-block">
<div class="question">
1. Which one is the biggest?
</div>
<div class="answers">
<form>
<input type="radio" name="1" value="1" checked> Elephant<br>
<input type="radio" name="1" value="2"> Whale<br>
<input type="radio" name="1" value="3"> Giraffe
</form>
</div>
</div>
<div class="question-block">
<div class="question">
2. Which one is the smallest animal?
</div>
<div class="answers">
<form>
<input type="radio" name="2" value="1" checked> Bacteria<br>
<input type="radio" name="2" value="2"> Virus<br>
<input type="radio" name="2" value="3"> Ant
</form>
</div>
</div>
<div id="result">
</div>

Related

changing the input class of a radio button dynamically with javascript

I am trying to make a small question web app using javascript/html. what I am trying to do is, assign a class to each of the radio buttons for each question-i.e. all the radio buttons for question 1 will have an input class of "question1" and 2 will have a class of "question2" and so on.
Because I don't know how many questions I will have, I was wondering if there was a way to achieve this dynamically through javascript using element.classList.add and increment the value of the question by 1 each time. I have received a response using jquery, but I was wondering if there was also a way to achieve this using pure javascript.
After some research, I have tried accessing all the elements inside a form using "form.elements" however it does not seem to be working.
HTML:
<form name="quizForm">
<div class="content">
<div class="quiz">
<p>Question 1</p>
<input type="radio" name="answer" value="1">
<input type="radio" name="answer" value="2">
<input type="radio" name="answer" value="3">
</div>
<div class="quiz" style="display: none;">
<p>Question 2</p>
<input type="radio" name="answer" value="1">
<input type="radio" name="answer" value="2">
<input type="radio" name="answer" value="3">
</div>
<div class="quiz" style="display: none;">
<p>Question 3</p>
<input type="radio" name="answer" value="1">
<input type="radio" name="answer" value="2">
<input type="radio" name="answer" value="3">
</div>
</form>
Javascript:
//counting the index of the class
let ind =0;
//access the named elements within the form
let elements = form.elements;
for(i=0;i<elements.length;i++){
element.classList.add(`quiz${ind+1}`)
}
Any information towards the right direction is greatly appreciated. Thank you.
I apologise for my initial question as I am realising that I have been unclear explaining some aspects of the issue that I was having. I managed to solve the problem. When I ask questions in the future, I will make sure I double check my code so that it is working. Posting an solution here for those who are interested and in the hopes that it will help someone.
What I did:
make a variable that keeps a track of the class number (ind)
using "querySelectorAll" I can select all the elements with the class "quiz"
loop through the returned array with forEach, increment the "ind" variable
select all the inputs that are inside each "quiz"
the "quiz" loop through those inputs and add a class to the input elements
HTML:
<div class="quiz">
<p>Question 1</p>
<input type="radio" name="answer" value="1">
<input type="radio" name="answer" value="2">
<input type="radio" name="answer" value="3">
</div>
<div class="quiz" style="display: none;">
<p>Question 2</p>
<input type="radio" name="answer" value="1">
<input type="radio" name="answer" value="2">
<input type="radio" name="answer" value="3">
</div>
<div class="quiz" style="display: none;">
<p>Question 3</p>
<input type="radio" name="answer" value="1">
<input type="radio" name="answer" value="2">
<input type="radio" name="answer" value="3">
</div>
Javascript:
const quizes = document.querySelectorAll('.quiz');
//a variable to increment the classes
let ind = 0;
quizes.forEach(function(element){
ind++;
let inputs = element.querySelectorAll('input');
inputs.forEach((input)=>{
input.classList.add(`question${ind}`)
})
//to test on the console
console.log(inputs)
})
All the radio button inputs for question 1 have the same "question1" class.

How to show specific value when click on any radio button in console using JavaScript?

I am having difficulty to show a value of selected radio button. When I click on question 1 then result 1 should be display on console but I am getting all the values of radio button.Can anyone help me please? Thanks
html
<form onsubmit="return answers(event)">
<label>Question 1</label>
<input type="radio" class="question" value="1">
<label>Question 2</label>
<input type="radio" class="question" value="2">
<label>Question 3</label>
<input type="radio" class="question" value="3">
<button type="submit">Submit</button>
</form>
JavaScript
<script>
function answers(event)
{
var q = document.querySelectorAll('.question');
[...q].forEach(question =>{
console.log(question.value);
});
event.preventDefault();
}
</script>
You could check to see if it is checked with question.checked.
function answers(event)
{
var q = document.querySelectorAll('.question');
[...q].forEach(question =>{
if(question.checked){
console.log(question.value);
}
});
event.preventDefault();
}
You might also want to add names to all the radios, because the idea of radios is that only one of them can be ticked at a time. name does that for you:
<form onsubmit="return answers(event)">
<label>Question 1</label>
<input type="radio" class="question" value="1" name="question">
<label>Question 2</label>
<input type="radio" class="question" value="2" name="question">
<label>Question 3</label>
<input type="radio" class="question" value="3" name="question">
<button type="submit">Submit</button>
</form>
Instead of checking the checked property inside a loop. You could use the :checked pseudo-class to only select checked radios.
function answers(event)
{
var q = document.querySelectorAll('.question:checked');
[...q].forEach(question =>{
console.log(question.value);
});
event.preventDefault();
}
<form onsubmit="return answers(event)">
<label>Question 1</label>
<input type="radio" class="question" value="1" name="question">
<label>Question 2</label>
<input type="radio" class="question" value="2" name="question">
<label>Question 3</label>
<input type="radio" class="question" value="3" name="question">
<button type="submit">Submit</button>
</form>
Also be aware to use the name property to group radio buttons.

Default checked button

Below code is html produced from opencart 2
No radio button is selected when loading page.
How can i have selected the Value="2" as default checked. (javascript or CSS)
<div id="payment-custom-field1" class="form-group custom-field" data-sort="0">
<label class="control-label">Invoice</label>
<div id="input-payment-custom-field1">
<div class="radio">
<label>
<input type="radio" value="2" name="custom_field[1]">
Receipt
</label>
</div>
<div class="radio">
<label>
<input type="radio" value="1" name="custom_field[1]">
Invoice
</label>
</div>
</div>
</div>
Solution with javascript
(function() {
document.getElementsByName("custom_field[1]")[0].checked=true;
})();
<input type="radio" id="sample" value="2" name="custom_field[1]">
Receipt
</label>
Using javascript:
document.getElementById("sample").checked = true;
Using html:
You can simply add checked attribute to your html element
Using the element name:
(function() {
document.getElementsByName("custom_field[1]")[0].checked=true;
})();
https://jsfiddle.net/pandiyancool/vb73q59w/
You can simply add checked attribute
<input type="radio" value="2" name="custom_field[1]" checked>
The solution with javascript was the below code:
document.getElementsByName("custom_field[1]")[0].checked=tru‌​e;
Thank you Pandiyan Cool

Check if any radio button is checked, than execute code (multiple sets of buttons)

I made a multiple choice test with parsing XML of questions and answers using PHP. The generated HTML looks something like this:
<form>
<div id="category0">
<div id="set0">
<div class="question">What is 6 x 6?</div>
<input type="radio" name="0" value="3">3<br>
<input type="radio" name="0" value="30">30<br>
<input type="radio" name="0" value="36">36<br>
<input type="hidden" class="answer" value="36">
</div>
<div id="set1">
<div class="question">What is 2 x 6?</div>
<input type="radio" name="1" value="4">4<br>
<input type="radio" name="1" value="12">12<br>
<input type="radio" name="1" value="36">43<br>
<input type="hidden" class="answer" value="12">
</div>
<!-- A LOT MORE QUESTIONS -->
</div>
<div id="category1">
<div id="set2">
<div class="question">Which of these tools would you use to hammer a nail?</div>
<input type="radio" name="2" value="A hammer">A hammer<br>
<input type="radio" name="2" value="Another nail">Another nail<br>
<input type="radio" name="2" value="A saw">A saw<br>
<input type="hidden" class="answer" value="A hammer">
</div>
<div id="set3">
<div class="question">What color is a red truck?</div>
<input type="radio" name="3" value="red">red<br>
<input type="radio" name="3" value="blue">blue<br>
<input type="radio" name="3" value="green">green<br>
<input type="hidden" class="answer" value="red">
</div>
<!-- A LOT MORE QUESTIONS -->
</div>
<!-- MORE CATEGORIES WITH A LOT OF QUESTIONS-->
</form>
Categories are named "Category" + a number starting from 0 (category0, category1...)
The answer is stored in a hidden field and is exactly the same as the correct options value.
I created a JS function that checks if the selected answer is correct or not, and colors the background of set div according. The function is triggered onclick in each radio input.
I need help with creating a statistic/score of answers for all questions and for each category separately.
At the beginning the score would be 0 of all possible answers.
If I would click on the correct choice of first question the score would be 1 of all possible questions, and 1 of all questions of first category.
I would like to achive this live (when any button is clicked), without posting the form(no POST/GET).
Hope I described my problem so you can understand it, if any clarification is needed, please let me know.
So far I only worked with JS, but any solutions in jQuery as also welcome.
When a radio button is clicked, execute the same logic you already have to determine if answers are correct, but call it for EACH of your "categories", NOT just the one that was clicked.
Start a variable at 0 and increment it by 1 each time you find a correct answer. Then, after your loop, you can update your "Correct Answers" message with the variable's value. This won't require any postbacks.
You could do something like this
$('input[type="radio"]').change( function(){
var answer = $(this).siblings('.answer').val();
if ($(this).val() == answer) {
var score = $(this).parents().siblings('.score').val();
score++;
$(this).parents().siblings('.score').val(score)
console.log(score);
} else {
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form>
<div id="category0">
<div id="set0">
<div class="question">What is 6 x 6?</div>
<input type="radio" name="0" value="3">3<br>
<input type="radio" name="0" value="30">30<br>
<input type="radio" name="0" value="36">36<br>
<input type="hidden" class="answer" value="36">
</div>
<div id="set1">
<div class="question">What is 2 x 6?</div>
<input type="radio" name="1" value="4">4<br>
<input type="radio" name="1" value="12">12<br>
<input type="radio" name="1" value="36">43<br>
<input type="hidden" class="answer" value="12">
</div>
<input type="hidden" class="score" value="0">
<p></p>
<!-- A LOT MORE QUESTIONS -->
</div>
<div id="category1">
<div id="set2">
<div class="question">Which of these tools would you use to hammer a nail?</div>
<input type="radio" name="2" value="A hammer">A hammer<br>
<input type="radio" name="2" value="Another nail">Another nail<br>
<input type="radio" name="2" value="A saw">A saw<br>
<input type="hidden" class="answer" value="A hammer">
</div>
<div id="set3">
<div class="question">What color is a red truck?</div>
<input type="radio" name="3" value="red">red<br>
<input type="radio" name="3" value="blue">blue<br>
<input type="radio" name="3" value="green">green<br>
<input type="hidden" class="answer" value="red">
</div>
<input type="hidden" class="score" value="0">
<p><p>
<!-- A LOT MORE QUESTIONS -->
</div>
<!-- MORE CATEGORIES WITH A LOT OF QUESTIONS-->
</form>

Previous correct radio buttons disappearing when I miss a radio button in the middle

I'm facing one issue here,
I am trying to validate at least one radio button to be answered to each question,
but the error here is when I miss some question to answer, I am getting alert, it is fine, but my previous correct answers also disappearing, I mean the page is loading from the start it seems.
Workingfiddle here.
You can see my sample question form here:
<form name="myform" >
<div id="Q1" class="question">
<h3>1. How convenient is our company to use?</h3>
</div>
<div id="A1"class="answers">
<input type="radio" name="Q1ans" value="1">Extremely convenient<br>
<input type="radio" name="Q1ans" value="2">Very convenient<br>
<input type="radio" name="Q1ans" value="3">Moderately convenient<br>
<input type="radio" name="Q1ans" value="4">Not at all convenient<br>
</div>
<div id="Q2" class="question">
<h3>2. How professional is our company?</h3>
</div>
<div id="A2"class="answers">
<input type="radio" name="Q2ans" value="1">Extremely professional<br>
<input type="radio" name="Q2ans" value="2">Very professional<br>
<input type="radio" name="Q2ans" value="3">Moderately professional<br>
<input type="radio" name="Q2ans" value="4">Not at all professional<br>
</div>
<div id="Q3" class="question">
<h3>3. Compared to our competitors, is our product quality better, worse, or about the same?</h3>
</div>
<div id="A3"class="answers">
<input type="radio" name="Q3ans" value="1">Much better<br>
<input type="radio" name="Q3ans" value="2">some what better<br>
<input type="radio" name="Q3ans" value="3">slightly better<br>
<input type="radio" name="Q3ans" value="4">worse<br>
</div>
<div id="Q4" class="question">
<h3>4. How responsive is our company?</h3>
</div>
<div id="A4"class="answers">
<input type="radio" name="Q4ans" value="1">Much better<br>
<input type="radio" name="Q4ans" value="2">some what better<br>
<input type="radio" name="Q4ans" value="3">slightly better<br>
<input type="radio" name="Q4ans" value="4">worse<br>
</div>
<div id="Q5" class="question">
<h3>5. Do you like our company, neither like nor dislike it, or dislike it?</h3>
</div>
<div id="A5"class="answers">
<input type="radio" name="Q5ans" value="1">Like a great deal<br>
<input type="radio" name="Q5ans" value="2">Like a little<br>
<input type="radio" name="Q5ans" value="3">Dislike a little<br>
<input type="radio" name="Q5ans" value="4">Dislike a great deal<br>
</div><br><br>
<button type="submit" onclick="validate()">submit</button>
</form>
You could simply change:
onclick="validate()"
to:
onclick="return validate()"
and it will have the desired behavior. I think this is what you were trying to do, but the onclick() call never returned the value from validate().

Categories