javascript ラジオボックスの値を取得する

javascript ラジオボックスの値を取得する

javascriptで、ラジオボックスの値を取得するサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 103.0.5060.134

取得方法

「group.value」を使用することで、チェックされている値を取得可能です。

<form id="foo">
<input type="radio" name="group" value="1" checked>
<input type="radio" name="group" value="2">
</form>

<script>

let hoge = document.getElementById("foo");
console.log(hoge.group.value); // checked なので 1が表示される

</script>

サンプルコード

以下は、
ラジオボタンを選択するたびに、値を表示する
サンプルコードとなります。

※cssには「bootstrap material」を使用してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons">
  <link rel="stylesheet"
    href="https://unpkg.com/bootstrap-material-design@4.1.1/dist/css/bootstrap-material-design.min.css"
    integrity="sha384-wXznGJNEXNG1NFsbm0ugrLFMQPWswR3lds2VeinahP8N0zJw9VWSopbjv2x7WCvX" crossorigin="anonymous">
</head>
<style>
  .main {
    margin: 0 auto;
    margin-top: 200px;
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 25px;
    width: 800px;
  }
</style>
<script>

  window.onload = function () {

    let hoge = document.getElementById("foo");
    
    // 選択した際のイベント取得
    hoge.addEventListener('change', (event) => {
      document.getElementsByClassName('badge-primary')[0].textContent = hoge.gridRadios.value;
    });

  }

</script>

<body>
  <div class="main">

    <h2><span class="badge badge-primary">選択した値</span></h2>

    <form id="foo">
      
      <fieldset class="form-group">
        <div class="row">          
          <div class="col-sm-12">
            <div class="form-check">
              <input class="form-check-input" type="radio" name="gridRadios" id="gridRadios1" value="First radio" checked>
              <label class="form-check-label" for="gridRadios1">
                First radio
              </label>
            </div>
            <div class="form-check">
              <input class="form-check-input" type="radio" name="gridRadios" id="gridRadios2" value="Second radio">
              <label class="form-check-label" for="gridRadios2">
                Second radio
              </label>
            </div>
            <div class="form-check disabled">
              <input class="form-check-input" type="radio" name="gridRadios" id="gridRadios3" value="Third radio">
              <label class="form-check-label" for="gridRadios3">
                Third radio
              </label>
            </div>
          </div>
        </div>
      </fieldset>
      
    </form>

  </div>
</body>

</html>

取得されていることが確認できます。