Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

69
70

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

jQuery で select タグに option タグを追加する

Last updated at Posted at 2015-05-08

例えば <select class="my-select" multiple> という select タグに
jQuery を使って option タグを追加してみます。

var characters = {
        yuno: 'ゆの',
        miyako: '宮子',
        sae: '沙英',
        hiro: 'ヒロ',
        nori: '乃莉',
        nazuna: 'なずな'
    },
    $select = $('.my-select'),
    $option,
    isSelected;

$.each(characters, function (value, name) {
    isSelected = (value === 'miyako' || value === 'nori');
    $option = $('<option>')
        .val(value)
        .text(name)
        .prop('selected', isSelected);
    $select.append($option);
});

val メソッドで value 属性を、text メソッドでテキストを、
prop メソッドで任意の属性 (今回の例では selected 属性) を option タグに設定します。
そして append メソッドを使って select タグに option タグを追加します。

options.png

できたぞ! \\\٩( 'ω' )و////

追記

@takeyuichi さんからアドバイスを頂きました。ありがとうございます!

  1. タグの生成時にオブジェクトで属性を指定できる。 (参考)
  2. ループ内での DOM 要素の追加はコストが高いので、ループ外で一括で追加する。 (参考)

以上の助言を元にソースコードを更新してみました。

var characters = {
        yuno: 'ゆの',
        miyako: '宮子',
        sae: '沙英',
        hiro: 'ヒロ',
        nori: '乃莉',
        nazuna: 'なずな'
    },
    $select = $('.my-select'),
    $option,
    options,
    isSelected;

// コールバック関数の引数の順序が $.each と異なることに注意。
options = $.map(characters, function (name, value) {
    isSelected = (value === 'miyako' || value === 'nori');
    $option = $('<option>', { value: value, text: name, selected: isSelected });
    return $option;
});

$select.append(options);
69
70
2

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

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details
69
70

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?