Lesson 19: Radio Buttons
Learn how to work with radio buttons in JavaScript to create single-selection interfaces and forms.
19.1 Understanding Radio Buttons
Radio buttons are form controls that allow users to select one option from a group of mutually exclusive choices. They are essential for forms where only one selection is allowed.
19.1.1 Basic Radio Button Selection
Example 19.1: Fruit Selection
This example shows how to get the selected radio button value using JavaScript.
// HTML
<form id="fruitForm">
<div class="radio-group">
<div class="radio-option">
<input type="radio" id="apple" name="fruit" value="Apple">
<label for="apple">Apple</label>
</div>
<div class="radio-option">
<input type="radio" id="orange" name="fruit" value="Orange">
<label for="orange">Orange</label>
</div>
<div class="radio-option">
<input type="radio" id="grape" name="fruit" value="Grape">
<label for="grape">Grape</label>
</div>
<div class="radio-option">
<input type="radio" id="melon" name="fruit" value="Melon">
<label for="melon">Melon</label>
</div>
</div>
<button type="button" onclick="getSelectedFruit()">
Get Selection
</button>
</form>
// JavaScript
function getSelectedFruit() {
const selectedFruit = document.querySelector(
'input[name="fruit"]:checked'
);
if (selectedFruit) {
alert(selectedFruit.value + " is selected");
} else {
alert("Please select a fruit");
}
}
19.1.2 Changing Content Based on Selection
Example 19.2: Dice Roller
This example demonstrates how to change an image based on the selected radio button.
// HTML
<div class="radio-group">
<div class="radio-option">
<input type="radio" id="one" name="dice" value="1" checked>
<label for="one">One Dot</label>
</div>
<div class="radio-option">
<input type="radio" id="two" name="dice" value="2">
<label for="two">Two Dots</label>
</div>
<!-- More options -->
</div>
<div class="dice-container">
<img id="diceImage" src="dice1.png" class="dice-image">
</div>
// JavaScript
document.querySelectorAll('input[name="dice"]').forEach(radio => {
radio.addEventListener('change', function() {
if (this.checked) {
const diceValue = this.value;
document.getElementById('diceImage').src =
`dice${diceValue}.png`;
}
});
});
19.2 Advanced Radio Button Techniques
Explore more sophisticated techniques for working with radio buttons in real-world applications.
19.2.1 Real-time Theme Switcher
Example 19.3: Theme Selection
This example shows how to change the page theme in real-time using radio buttons.
// HTML
<div class="theme-switcher">
<div class="theme-card" data-theme="default">
<div class="theme-preview" style="background: linear-gradient(135deg, #1a73e8, #0d47a1)"></div>
<span>Blue Theme</span>
</div>
<div class="theme-card" data-theme="green">
<div class="theme-preview" style="background: linear-gradient(135deg, #4caf50, #2e7d32)"></div>
<span>Green Theme</span>
</div>
<!-- More themes -->
</div>
// JavaScript
document.querySelectorAll('.theme-card').forEach(card => {
card.addEventListener('click', function() {
const theme = this.getAttribute('data-theme');
document.body.className = theme;
// Update UI
document.querySelectorAll('.theme-card').forEach(c => {
c.classList.remove('selected');
});
this.classList.add('selected');
});
});
Select a theme to see the preview. The theme will be applied to this demo area.
Current theme: Default
19.2.2 Radio Buttons in Forms
Example 19.4: Survey Form with Validation
This example demonstrates a survey form with radio button validation using the onsubmit event.
// HTML
<form id="surveyForm" onsubmit="return validateSurvey()">
<div class="form-group">
<label>How satisfied are you with our service?</label>
<div class="radio-group">
<div class="radio-option">
<input type="radio" id="verySatisfied" name="satisfaction" value="Very Satisfied">
<label for="verySatisfied">Very Satisfied</label>
</div>
<!-- More options -->
</div>
</div>
<button type="submit" class="submit-btn">Submit Survey</button>
<div class="validation-summary" id="surveyValidation">
<h4>Please fix the following errors:</h4>
<ul id="surveyErrors"></ul>
</div>
</form>
// JavaScript
function validateSurvey() {
const satisfaction = document.querySelector(
'input[name="satisfaction"]:checked'
);
const errors = [];
if (!satisfaction) {
errors.push("Please select your satisfaction level");
}
if (errors.length > 0) {
const errorList = document.getElementById('surveyErrors');
errorList.innerHTML = errors.map(e => `<li>${e}</li>`).join('');
document.getElementById('surveyValidation').style.display = 'block';
return false;
}
// Form is valid
alert("Survey submitted successfully!");
return true;
}
19.3 Real-World Applications
These radio button techniques are essential in many web applications. Here are practical examples:
19.3.1 Quiz Application
Example 19.5: Multiple Choice Quiz
This example demonstrates a quiz application using radio buttons to select answers.
// HTML
<div class="quiz-container">
<div class="quiz-question">
<h4>What is the capital of France?</h4>
<div class="radio-group">
<div class="radio-option">
<input type="radio" id="q1a" name="q1" value="A">
<label for="q1a">London</label>
</div>
<!-- More options -->
</div>
</div>
<button type="button" onclick="checkAnswers()">
Check Answers
</button>
<div class="quiz-result" id="quizResult"></div>
</div>
// JavaScript
function checkAnswers() {
const answers = {
q1: "C", // Correct answer for question 1
q2: "B" // Correct answer for question 2
};
let score = 0;
// Check question 1
const q1Answer = document.querySelector('input[name="q1"]:checked');
if (q1Answer && q1Answer.value === answers.q1) {
score++;
}
// Display results
const resultDiv = document.getElementById('quizResult');
resultDiv.innerHTML = `<h3>Quiz Results</h3>
<p>You scored ${score} out of 2!</p>`;
resultDiv.style.display = 'block';
}