jquery セレクトボックスで選択している値とラベルを取得する

jquery セレクトボックスで選択している値とラベルを取得する

jqueryで、セレクトボックスで選択している値とラベルを取得するサンプルコードを記述してます。「val」と「option:selected」メソッドを使用してます。

環境

  • OS windows10 pro 64bit
  • jquery 3.6.0
  • Apache 2.4.43
  • ブラウザ chrome 91.0.4472.77

セレクトボックスで選択している値とラベルを取得

セレクトボックスで選択している値とラベルを取得するには、「val」と「option:selected」を使用します。

$('[name="selectのname"]').val() // 値
$('[name="selectのname"] option:selected').text() // ラベル

以下は、「実行」ボタンをクリックすると、セレクトボックスで選択している値とラベルを取得して表示するサンプルコードを記述してます。

※デザインは「semantic-ui」を使用してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <!-- semantic.css  -->
  <link rel="stylesheet" type="text/css"
    href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css">
  <script src="http://code.jquery.com/jquery-3.6.0.min.js"></script>

</head>
<style>
  body>.grid {
    height: 100%;
  }

  .fields {
    margin-top: 5px;
  }
</style>
<script>

$(function() {

  $('#btn').on('click', function() {

    $('#result').text( `value = ${$('[name="sel"]').val()} label = ${$('[name="sel"] option:selected').text()}`)

  })

})

</script>

<body>

  <div class="ui middle center aligned grid">

    <div class="column">

      <h2 id="result"></h2>

      <form class="ui fluid form">
        <div class="inline field">
          <select name="sel" class="ui fluid dropdown">
            <option value="AL">Alabama</option>
            <option value="AK">Alaska</option>
            <option value="AZ">Arizona</option>
          </select>
        </div>
      </form>

      <div class="ui inline stackable fields">
        <button id="btn" class="ui green inverted button">実行</button>
      </div>

    </div>
  </div>
</body>

</html>

取得されていることが確認できます。

また、以下のようにアロー関数を使用して記述することも可能です。
※アロー関数を使用するとthisの挙動が異なります。

$(() => {

  $('#btn').on('click', () => {

    $('#result').text( `value = ${$('[name="sel"]').val()} label = ${$('[name="sel"] option:selected').text()}`)

  })

})