【JavaScript】ラジオボタンで選択項目に応じて表示を切り替える

ラジオボタンで選択項目に応じて表示を切り替える

この記事では、ラジオボタンを選択したときの表示の切り替える動きのJavaScriptでの実装方法をまとめていきます。

INDEX

選択項目に応じて表示を切り替える

デモはこちらです。

See the Pen [JavaScript]入力フォームの選択項目に応じて内容を切り替える by asamifuruta (@asamih5) on CodePen.

HTML

<p>選択してください</p>
<div class="choice_wrap">
  <input type="radio" name="switching" id="choice_a" checked>
  <label for="choice_a">選択肢A</label>
  <!-- 以下を初期表示とA選択時に表示 -->
  <div class="select_card_a">
    Aを選択すると表示します。Bを選択すると非表示になります。
  </div>
</div>

<div class="choice_wrap">
  <input type="radio" name="switching" id="choice_b">
  <label for="choice_b">選択肢B</label>
  <!-- 以下をB選択時に表示 -->
  <div class="select_card_b" style="display: none;">
    Bを選択すると表示します。Aを選択すると非表示になります。
  </div>
</div>

CSS

レイアウトのための記述です。デザインの合わせて変更してください。

.choice_wrap {
  margin-bottom: 1rem;
}
.select_card, .select_card2 {
  margin-left: 1.5rem;
}

JavaScript

それぞれ選択したときの処理を書きます。

name=”switching”のラジオボタンの#choice_aにチェックが入っているとき、.select_card_aを表示。#choice_bにチェックが入っているときは、.select_card_aを非表示。

$(function() {
  $('[name="switching"]:radio').change( function() {
    if($('[id=choice_a]').prop('checked')){
      $('.select_card_a').show();
    } else if ($('[id=choice_b]').prop('checked')) {
      $('.select_card_a').hide();
    }
  });
});

name=”switching”のラジオボタンの#choice_bにチェックが入っているとき、.select_card_bを表示。#choice_aにチェックが入っているときは、.select_card_bを非表示。

$(function() {
  $('[name="switching"]:radio').change( function() {
    if($('[id=choice_b]').prop('checked')){
      $('.select_card_b').show();
    } else if ($('[id=choice_a]').prop('checked')) {
      $('.select_card_b').hide();
    } 
  });
});

メモ

簡単な仕組みですが、実装するのに迷ってしまったので記録に残しました。入力フォームでよく見る動きですのでさまざまなサイトに応用できそうです。

よかったらシェアしてね!
  • URLをコピーしました!

この記事を書いた人

INDEX