Check if any radio input is checked

if (document.querySelector("input[name='maca']")).getAttribute("checked")
<input type="radio" name="maca" id="maca1">
<input type="radio" name="maca" id="maca2">

I want to check if any one of the input type radio buttons with the same name is checked.

>Solution :

Select every radio button with that name with querySelectorAll, then use Array.some to check whether one of the items in the list is checked:

const radioButtons = document.querySelectorAll('input[name="maca"]')
const oneChecked = [...radioButtons].some(e => e.checked)
console.log(oneChecked)
<input type="radio" name="maca" id="maca1">
<input type="radio" name="maca" id="maca2" checked>

Alternatively, you can try selecting the checked radio button (with the :checked pseudo-class) and see if an element was selected:

if(document.querySelector('input[name="maca"]:checked')){
  console.log('checked')
}
<input type="radio" name="maca" id="maca1">
<input type="radio" name="maca" id="maca2" checked>

Leave a Reply