Get the value of selected radio button in JavaScript
Question:
How to get the value of selected radio button in JavaScript? Answer:
const selectedColor = document.querySelector('input[name="color"]:checked').value;
Description:
Even if HTML radio buttons look a bit different compared to a simple text input, getting the selected value is the same. You need to read the value
property of the selected element. So the only difficulty is to get the right element. To do this you can use the querySelector
method with a selector that selects only the checked value from the radio items.
The code above reads the value from the following radio buttons:
<input type="radio" name="color" value="1"> Red
<input type="radio" name="color" value="2"> Green
<input type="radio" name="color" value="3" checked="checked"> Blue
Reference:
The querySelector reference
Share "How to get the value of selected radio button in JavaScript?"
Related snippets:
- Create HTML element with attributes in JavaScript
- Get element by ID in React
- Set the required attribute in JavaScript
- Get elements by data attribute in JavaScript
- Add class to the clicked element in JavaScript
- Add class to multiple elements in JavaScript
- Add class to element if it does not already exists with JavaScript
- Add data attribute to element in JavaScript
- Add CSS class to body with JavaScript
- Add class to parent element in JavaScript
- Toggle fullscreen and normal mode with JavaScript
- Play video in fullscreen with vanilla JavaScript
- Select HTML elements by CSS selectors in vanilla JavaScript
- Exit from fullscreen mode on click in JavaScript
- Switch browser to fullscreen mode with JavaScript
- Get the value of text input field in JavaScript
- Get element with data- attribute using vanilla JavaScript
- Get the value of selected radio button in JavaScript
- Get selected option from select using JavaScript
- Check if element is hidden in JavaScript
Tags:
html, radio, radio button, value, vanilla, JavaScript Technical term:
Get the value of selected radio button in JavaScript