LoginSignup
13

More than 5 years have passed since last update.

JQuery: Bootstrap popover のcontent htmlの手動セットとcloseボタン設置

Last updated at Posted at 2015-05-24

Railsで作ったデータベースで、同姓同名のデータがある場合に、その一覧を Bootstrap の popover で表示するようにしたかった(下図のような感じ)。
fig01.png

姓名のフィールドに入力があった時点で、JQueryのchangeイベントを受けて、検索するアクションをたたいて、getJSONで受け取って表示すればよい。

BootstrapページのpopoverのサンプルはButtonにメッセージを設定して、クリックなどで表示させるものだが、自分で検索の都度にcontentを設定したいし、また、popoverを消すためのcloseボタンも設置したい。どうするか?

まずは、表示したい場所にdivを書く。

<div id="popoverSameNames"></div>

これに対して、popover で content を設定して、show すればよい。

popover.({options}) の中でcontentを指定することもできるが、それだと、再検索したときに表示が切り替わらないことが判明。

こちらにヒントがあった
Bootstrap popover content cannot changed dynamically
書き換えるたびに以下のようにすればよいようだ。

$("#popoverSameNames").data('bs.popover').options.content = samenames_html;

また、closeボタンのつけ方は以下にあった。
How to add a close button to Bootstrap Popover

最終的に以下のようなコードにした。

// getJSONで受け取った同姓同名の情報から samenames_html を作って↓
if (samenames_html.length > 0) {
  $("#popoverSameNames").popover({ 
    title: '同姓同名があります.<span class="close">&times;</span>',
    template: '<div class="popover" role="tooltip" style="width:500px;font-size:80%;"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"><div class="data-content"></div></div></div>',
    html: true
  }).on('shown.bs.popover', function(e){
    var popover = $(this);
    $(this).parent().find('div.popover .close').on('click', function(e){
      popover.popover('hide');
    });
  });
  $("#popoverSameNames").data('bs.popover').options.content = samenames_html;
  $("#popoverSameNames").popover('show');
} else {
  $("#popoverSameNames").data('bs.popover').options.content = "";
  $("#popoverSameNames").popover('hide');
}

これでとりあえずうまく動いている。

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
13