【初心者向け】JavaScriptでラジオボタンのvalue値を取得する方法を徹底解説

2024-04-11

JavaScriptで選択されたラジオボタンの値を取得する方法

<form id="form1">
  <label for="red"></label>
  <input type="radio" id="red" name="color" value="red" checked>
  <label for="blue"></label>
  <input type="radio" id="blue" name="color" value="blue">
  <label for="green"></label>
  <input type="radio" id="green" name="color" value="green">
</form>

JavaScript

// 1. document.querySelector()を使う

const selectedRadioButton = document.querySelector('input[name="color"]:checked');
const selectedValue = selectedRadioButton.value;

console.log(selectedValue); // "red"

// 2. forEach()を使う

const radioButtons = document.querySelectorAll('input[name="color"]');

for (const radioButton of radioButtons) {
  if (radioButton.checked) {
    console.log(radioButton.value); // "red"
    break;
  }
}

// 3. document.formsを使う

const form = document.getElementById('form1');
const selectedValue = form.elements['color'].value;

console.log(selectedValue); // "red"

解説

上記3つの方法は、それぞれ異なる方法で選択されたラジオボタンの値を取得します。

document.querySelector()を使って、name属性がcolorで、checked属性がtrueのラジオボタンを取得します。

forEach()を使う

querySelectorAll()を使って、name属性がcolorのすべてのラジオボタンを取得し、forEach()を使ってループ処理します。ループ処理の中で、checked属性がtrueのラジオボタンを見つけたら、その値を出力します。

document.formsを使って、id属性がform1のフォームを取得し、elementsプロパティを使って、name属性がcolorのラジオボタンの値を取得します。

  • シンプルな方法で選択されたラジオボタンの値を取得したい場合は、document.querySelector()を使う方法がおすすめです。
  • 複数のラジオボタンの値を取得したい場合は、forEach()を使う方法がおすすめです。
  • フォーム全体を操作したい場合は、document.formsを使う方法がおすすめです。



HTML

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>選択されたラジオボタンの値を取得</title>
</head>
<body>
  <form id="form1">
    <label for="red"></label>
    <input type="radio" id="red" name="color" value="red" checked>
    <label for="blue"></label>
    <input type="radio" id="blue" name="color" value="blue">
    <label for="green"></label>
    <input type="radio" id="green" name="color" value="green">
  </form>

  <script src="script.js"></script>
</body>
</html>
// 1. document.querySelector()を使う

const selectedRadioButton = document.querySelector('input[name="color"]:checked');
const selectedValue = selectedRadioButton.value;

console.log(selectedValue); // "red"

// 2. forEach()を使う

const radioButtons = document.querySelectorAll('input[name="color"]');

for (const radioButton of radioButtons) {
  if (radioButton.checked) {
    console.log(radioButton.value); // "red"
    break;
  }
}

// 3. document.formsを使う

const form = document.getElementById('form1');
const selectedValue = form.elements['color'].value;

console.log(selectedValue); // "red"

実行方法

  1. 上記のHTMLコードとJavaScriptコードをそれぞれ別のファイルに保存します。
  2. HTMLファイルをブラウザで開きます。
  3. JavaScriptファイルの内容をブラウザの開発者ツールで実行します。

出力結果

red
red
red

補足

  • 上記のサンプルコードは、あくまでも基本的な例です。
  • 実際の開発では、状況に合わせてコードを修正する必要があります。



選択されたラジオボタンの値を取得する他の方法

getElementsByName()を使う

document.formsを使ってフォームを取得し、getElementsByTagName()を使ってラジオボタンの配列を取得します。その後、forループを使って配列をループ処理し、checked属性がtrueのラジオボタンを見つけたら、その値を出力します。

const form = document.getElementById('form1');
const radioButtons = form.getElementsByTagName('input');

for (const radioButton of radioButtons) {
  if (radioButton.type === 'radio' && radioButton.checked) {
    console.log(radioButton.value); // "red"
    break;
  }
}

jQueryライブラリを使っている場合は、$('input[name="color"]:checked').val()を使って、選択されたラジオボタンの値を取得できます。

$(document).ready(function() {
  const selectedValue = $('input[name="color"]:checked').val();

  console.log(selectedValue); // "red"
});

自作関数を使う

上記の方法を参考に、自作関数を作成して、選択されたラジオボタンの値を取得することもできます。

function getSelectedValue(formName, radioName) {
  const form = document.getElementById(formName);
  const radioButtons = form.getElementsByTagName('input');

  for (const radioButton of radioButtons) {
    if (radioButton.type === 'radio' && radioButton.name === radioName && radioButton.checked) {
      return radioButton.value;
    }
  }

  return null;
}

const selectedValue = getSelectedValue('form1', 'color');

console.log(selectedValue); // "red"
  • jQueryライブラリを使っている場合は、jQueryを使う方法がおすすめです。
  • コードをカスタマイズしたい場合は、自作関数を使う方法がおすすめです。

javascript html radio-button


setInterval() vs setTimeout(): 5秒間隔で実行する際の比較

setInterval() メソッドを使う解説setInterval() メソッドは、指定された間隔で関数を繰り返し実行します。第1引数には、実行する関数オブジェクトを渡します。第2引数には、実行間隔をミリ秒単位で渡します。この例では、5000ミリ秒なので5秒間隔になります。...


JavaScript/jQueryでフォームデータを取得して、Web開発をレベルアップ!

jQuery でフォームデータを取得する最も簡単な方法は、serialize() メソッドを使う方法です。このメソッドは、フォーム内のすべての入力要素の値をシリアル化し、クエリ文字列に変換します。serialize() メソッドは、フォーム内に複数の入力要素がある場合でも、すべての値を取得することができます。...


Node.jsでHTTPSサーバーを構築:初心者向けチュートリアル

まず、以下のライブラリをインストールする必要があります。node-forge: SSL/TLS証明書の生成と管理に使用します。fs: ファイルシステムへのアクセスに使用します。http2: HTTP/2プロトコルを実装するために使用します。...


JavaScript で数字に st、nd、rd、th (序数) サフィックスを追加する 3 つの方法

この方法は、序数サフィックスを追加する関数を定義することで、コードを簡潔に保つことができます。この関数は、以下のロジックに基づいています。数字の最後の桁 (ones) と、最後の 2 桁の最初の桁 (tens) を取得します。tens が 1 の場合は、"th" を返します。...


Map vs Object in JavaScript:完全ガイド(ECMAScript 6以降)

JavaScriptには、オブジェクトを格納するための2つの主要なデータ構造があります。ObjectとMapです。一見似ていますが、重要な違いがいくつかあります。このガイドでは、ECMAScript 6以降で導入されたMapと従来のObjectを比較し、それぞれの特徴、ユースケース、適切な使い分けについて詳しく解説します。...


SQL SQL SQL SQL Amazon で見る



JavaScript で選択されたラジオボタンの値を取得する方法

HTMLフォームでラジオボタンを使用する場合、ユーザーが選択したオプションの値を取得することが重要です。これは、フォームデータを処理したり、ユーザーの選択に基づいてダイナミックな動作をしたりするために役立ちます。このチュートリアルで使用するもの: