Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

例えば <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);
QUANON
あんた、マジなんだな?
http://quanon.github.io/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした