0
0

More than 1 year has passed since last update.

JavaScriptでラジオボタンの情報を取得

Last updated at Posted at 2020-07-28

「addEventListener()」を使った、チェックによるイベント処理の方法です。
「addEventListener()」とは、さまざまなイベント処理を実行することができるメソッドです。

  • 入力がされた
  • クリックがされた
  • ページが読み込まれた

などが発生した場合に「addEventListener()」を使って処理を実行できます。

書き方

対象要素.addEventListener( 種類, 関数, false )

■第1引数にイベントの種類を指定

■第2引数に関数を指定

■第3引数にイベント伝搬の方式を「true / false」で指定
通常はfalseを指定しておく。

ラジオボタンが押されたらvalueの情報を取得する

html
<form id="CheckBtn">
    <input type="radio" name="group" value="ラジオボタン1" checked> ラジオボタン1
    <input type="radio" name="group" value="ラジオボタン2"> ラジオボタン2
    <input type="radio" name="group" value="ラジオボタン3"> ラジオボタン3
</form>
javascript
const CheckBtn = document.getElementById('CheckBtn');
CheckBtn.addEventListener('change', function () {
  console.log(CheckBtn.group.value);
});

まとめ

ラジオボタンでサイトの装飾を変化させたときのコードです。

よく見るドロワーやアコーディオンメニューなどの機能も「addEventListener()」で作れるので、覚えておいても良いかも。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0