LoginSignup
30
19

More than 5 years have passed since last update.

【Rails】Bootstrap 4 でラジオボタンの見た目をトグルボタンにする

Last updated at Posted at 2017-11-03

やりたかったこと

  • ラジオボタンの見た目をかっこよくしたい(ザックリ)
  • inputのtype属性はradioのままで実現したい
  • CSSの編集は最低限にとどめたい

bootstrap_radiobutton1.png

やったこと

  • Bootstrap 4のButton pluginを適用

bootstrap_radiobutton2.png

詳細

Bootstrap 4の導入

RailsにBootstrap 4を導入する手順については下記の投稿で解説してます。

Railsアプリで Bootstrap 4 を利用する - Qiita

Button pluginの適用

Bootstrap 4の公式ドキュメントにチェックボックスやラジオボタンの見た目をボタンにするサンプルが掲載されていたので、こちらを参考に実装しました。

Button plugin / Checkbox and radio buttons

Before

bootstrap_radiobutton3.png

formのラジオボタン部分を抜粋
<div class="form-group row">
  <div class="col-sm-2">
    <%= f.label :sex, '性別', {class: 'form-label'} %>
  </div>
  <div class="col-sm-10">
    <%= f.radio_button :sex, 0, {checked: true} %> 男性
    <%= f.radio_button :sex, 1, {} %> 女性
  </div>
</div>

After

bootstrap_radiobutton4.png

formのラジオボタン部分を抜粋
<div class="form-group row">
  <div class="col-sm-2">
    <%= f.label :sex, '性別', {class: 'form-label'} %>
  </div>
  <div class="col-sm-10 btn-group" data-toggle="buttons">
    <label class="btn btn-outline-secondary active" style="width:50%">
      <%= f.radio_button :sex, 0, {checked: true} %> 男性
    </label>
    <label class="btn btn-outline-secondary" style="width:50%">
      <%= f.radio_button :sex, 1, {} %> 女性
    </label>
  </div>
</div>
30
19
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
30
19