crea un grupo de buttons radio en html in javascript

To create a group of radio buttons in HTML with JavaScript, you can follow these steps:

  1. First, create the HTML elements for the radio buttons and assign them a name to group them together:
<input type="radio" name="group-name" value="option-1"> Option 1
<br>
<input type="radio" name="group-name" value="option-2"> Option 2
<br>
<input type="radio" name="group-name" value="option-3"> Option 3
205 chars
6 lines
  1. Next, you can use JavaScript to add an event listener to each radio button that listens for a 'click' event. When a radio button is clicked, it updates a variable to store the selected option:
index.tsx
// Get all radio buttons by name
const radios = document.getElementsByName('group-name');

// Define a variable to store the selected option
let selectedOption;

// Loop through each radio button and add event listener
for (let i=0; i<radios.length; i++) {
  radios[i].addEventListener('click', function() {
    selectedOption = radios[i].value;
  });
}
354 chars
13 lines
  1. You can also use JavaScript to pre-select a radio button by default when the page loads:
index.tsx
// Pre-select the first option by default
radios[0].checked = true;
selectedOption = radios[0].value;
102 chars
4 lines

By creating an HTML group for the radio buttons and using JavaScript to add event listeners and store the selected option, you can easily create a group of radio buttons that behave as expected.

gistlibby LogSnag