ラジオボタン - Javascript

チェックされているラジオボタンの値の取得

index.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <script src="script.js"></script>
  <title>Document</title>
</head>
<body>
  <form action="">
    <p><label for="apple"><input type="radio" name="fruits" id="apple" value="apple">apple</label></p>
    <p><label for="orange"><input type="radio" name="fruits" id="orange" value="orange">orange</label></p>
    <p><label for="banana"><input type="radio" name="fruits" id="banana" value="banana">banana</label></p>
    <p><label for="cherry"><input type="radio" name="fruits" id="cherry" value="cherry">cherry</label></p>
    <p><button type="button" id="btn">button</button></p>
  </form>
</body>
</html>

script.js

window.onload = function(){
  const btn = document.getElementById('btn');
  const ele = document.getElementsByName('fruits');
  
  btn.addEventListener('click', function(){
    let checkValue = '';
    for(let i of ele){
      if(i.checked){
        checkValue = i.value;
      }
    }
    console.log(checkValue);
  });
}

ラジオボタンのチェックを外す

script.js

window.onload = function(){
  const btn = document.getElementById('btn');
  const ele = document.getElementsByName('fruits');

  btn.addEventListener('click', function(){
    for(let i of ele){
      i.checked = false;
    }
  });
}