LoginSignup
1

More than 3 years have passed since last update.

select2でajaxを使った場合に値をプログラム的に設定する

Last updated at Posted at 2019-06-16

はじめに

select2で、あらかじめ決まった値をセットしておきたいときってあるよね?
ajaxを使った場合、ドキュメントに書かれているやり方ではうまくいかなかったので、対応した時のメモです。

環境

  • Windows10
  • select2 4.0.6-rc.1

方法

例えば {id=4, text='aaa'} のデータをタグに設定しておきたいとする。
ajaxを使わない場合だと、以下でうまくいくが、ajaxを使っている場合、悲しいことに何も起こらない。

$(".js-example-basic-multiple").val('aaa').trigger("change");

この場合、以下のようにすればよい。

$(".js-example-basic-multiple").select2("trigger", "select", {data: { id: "4" , text: "aaa"}});

複数値をセットしたい場合は、以下のように複数回呼び出せばよい。

$(".js-example-basic-multiple").select2("trigger", "select", {data: { id: "4" , text: "aaa"}});
$(".js-example-basic-multiple").select2("trigger", "select", {data: { id: "5" , text: "aaaaaaa"}});

idやtextはサーバから取得されるものと整合性がとれていないと、当然ながら、おかしくなるだろう。

参考

Programmatically set the value of a Select2 ajax
https://stackoverflow.com/questions/25395427/programmatically-set-the-value-of-a-select2-ajax

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
1