2
2

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 3 years have passed since last update.

jQueryを使ってselectから任意の場所のoptionを拾う方法

Posted at

以下のようなセレクタがあったとします。

<select id="sample_selector">
  <option value="0">選択肢1</option>
  <option value="1">選択肢2</option>
  <option value="2">選択肢3</option>
  <option value="3">選択肢4</option>
  <option value="4">選択肢5</option>
</select>

ここから「最初の選択肢」や「最後の選択肢」などを引っ張ってきたい時に使えるjQuery構文の紹介。

■最初の選択肢:

$('#sample_selector').children('option:first-child').val()
$('#sample_selector').children('option:first-child').text()

■最後の選択肢:

$('#sample_selector').children('option:last-child').val()
$('#sample_selector').children('option:last-child').text()

■N番目の選択肢:

$('#sample_selector').children('option:nth-child(3)').val()
$('#sample_selector').children('option:nth-child(3)').text()

※この例なら選択肢3が対象となります。

今回はidを使いましたが、nameならセレクタを$('select[name=sample_selector]')に変えることで実現可能。

これを応用すると、select要素の最後のオプションを削除したりすることもできます。

2
2
1

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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?