11
5

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 1 year has passed since last update.

jQueryでセレクトボックスの値に応じて表示を変更する

Last updated at Posted at 2022-09-02

今回の完成形

こちらのようにセレクトボックスで3を選択した場合のみリンクを表示する実装をしていきます。

See the Pen Untitled (@katao_eng) on CodePen.

「えっ、今更jQueryキャッチアップするん?」

という声が聞こえてくるような気もしますが、業務で使用することがあるのでキャッチアップしていきます。

セレクトボックスの作成

HTMLでセレクトボックスを作成します。

sample.html
  <p>3を選択した時だけリンクを表示</p>

  <select name="select" id="select">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
  </select>

  <div id="link">
    <a href="https://qiita.com/">3の時だけ表示するリンク</a>
  </div>

この状態では常にリンクが表示されている状態なので、CSSでdisplay:noneを指定します。

sample.css
#link {
  display: none;
}

jQueryで関数を定義

sample.js
$(document).ready(function() {
  if ($('#select option:selected').text() === '3') {
    $('#link').show();
  }
  $('#select').on('change', function () {
    if ($('#select option:selected').text() === '3') {
      $('#link').show();
    } else {
      $('#link').hide();
    }
  });
});

セレクトボックスで選択されている値はoption:selectedで取得します。

最初のif文では、初期表示が3だった場合にリンクを表示するために記載しています。

  if ($('#select option:selected').text() === '3') {
    $('#link').show();
  }

本当はセレクトボックスで選択した値をcookieに保存して、再度アクセスした際に前回選択した値を初期表示にしたかったのですが、cookieの保存がうまくできませんでした... cookieの保存ができなかったのはローカルファイルで試していたからで、サーバーにアップしていなかったからでした。)
セレクトボックスの作成には記載していませんが、今回の完成形で実装したものは初期表示が3で表示されるようにvalue="3"のoptionタグにselectedを指定してます。

$('#select').on('change', function () {});

セレクトボックスで値が変更される都度、こちらの関数が実行されます。

最後に

正直もっと良い実装ができるんじゃないかと思っているのですが、今できるのはこの程度です。

  if ($('#select option:selected').text() === '3') {
    $('#link').show();
  }

特に、jQueryの最初のif文で初期表示が3だった場合のところですが、もっと良い書き方あるんじゃないのかなあと思っています。
指摘やアドバイスなどいただけると幸いです。
JavaScriptでもjQueryでもcookieが保存できなかったことも課題なので、その辺りのキャッチアップも進めていこうと思います。

11
5
5

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
11
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?