xxxxxxxxxx
<input type="radio" name="test" value="value1"> Value 1
<input type="radio" name="test" value="value2"> Value 2
<input type="radio" name="test" value="value3"> Value 3
xxxxxxxxxx
<!--Just manke both names equal -->
<input type="radio" name="options" id="1"/>
<input type="radio" name="options" id="2"/>
xxxxxxxxxx
<!-- Just give all the radio buttons the same name.
Html will then allow you to select only one. -->
<input type="radio" name="radAnswer" />
xxxxxxxxxx
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Radio Button</title>
</head>
<body>
<p>Select your size:</p>
<div id="group">
</div>
<p id="output"></p>
<script>
const sizes = ['XS', 'S', 'M', 'L', 'XL', 'XXL'];
// generate the radio groups
const group = document.querySelector("#group");
group.innerHTML = sizes.map((size) => `<div>
<input type="radio" name="size" value="${size}" id="${size}">
<label for="${size}">${size}</label>
</div>`).join(' ');
// add an event listener for the change event
const radioButtons = document.querySelectorAll('input[name="size"]');
for(const radioButton of radioButtons){
radioButton.addEventListener('change', showSelected);
}
function showSelected(e) {
console.log(e);
if (this.checked) {
document.querySelector('#output').innerText = `You selected ${this.value}`;
}
}
</script>
</body>
</html>
Code language: HTML, XML (xml)
xxxxxxxxxx
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Radio Button</title>
</head>
<body>
<p>Select your size:</p>
<div>
<input type="radio" name="size" value="XS" id="xs">
<label for="xs">XS</label>
</div>
<div>
<input type="radio" name="size" value="S" id="s">
<label for="s">S</label>
</div>
<div>
<input type="radio" name="size" value="M" id="m">
<label for="m">M</label>
</div>
<div>
<input type="radio" name="size" value="L" id="l">
<label for="l">L</label>
</div>
<div>
<input type="radio" name="size" value="XL" id="xl">
<label for="xl">XL</label>
</div>
<div>
<input type="radio" name="size" value="XXL" id="xxl">
<label for="xxl">XXL</label>
</div>
<p>
<button id="btn">Show Selected Value</button>
</p>
<p id="output"></p>
<script>
const btn = document.querySelector('#btn');
const radioButtons = document.querySelectorAll('input[name="size"]');
btn.addEventListener("click", () => {
let selectedSize;
for (const radioButton of radioButtons) {
if (radioButton.checked) {
selectedSize = radioButton.value;
break;
}
}
// show the output:
output.innerText = selectedSize ? `You selected ${selectedSize}` : `You haven't selected any size`;
});
</script>
</body>
</html>
Code language: HTML, XML (xml)