スニペット

HTMLのSelectボックスをJavaScriptで操作する方法

selectボックスをjavascriptで操作しよう

ニャンコ
ニャンコ

今回は、HTMLのSelectボックスをJavaScriptを使って動的に操作する方法について解説します。

この例では、Selectボックス内の年を増減させるボタンを設置し、それにより選択された年を変更できるようにします。
セレクトボックスとしても選択できるし、ボタンでも選択ができます。

コピペOKなので、色々改造して試してみてください。

ワンコ
ワンコ

動的に操作するセレクトボックスのサンプル

今回のサンプルが下記のセレクトボックスです。
セレクトボックスとして、選択も可能で、セレクトボックス右の上下の矢印でも選択が可能になっています。

See the Pen Untitled by kokusyo (@kokusyo) on CodePen.

動的に操作するセレクトボックスのコード

HTML

コード解説、まずはHTMLですが、特に変わったところはないと思います。
今回は、selectを操作するタグは、buttonで用意しました。

<!-- selectボックスをラップするクラス -->
<div class="year_selector">
    <select id="year_select">
        <option value="2021">2021年</option>
        <option value="2022">2022年</option>
        <option value="2023">2023年</option>
        <option value="2024">2024年</option>
        <option value="2025">2025年</option>
    </select>

    <!-- selectボックスを操作するボタン -->
    <div class="year_selector_btn">
        <!--デクリメントするボタン -->
        <button id="year_decrease"></button>
        <!-- インクリメントするボタン -->
        <button id="year_increase"></button>
    </div>
</div>

CSS

続いてCSSです。
デザインを整えているだけなので、特にポイントはありません。
矢印は、buttunの::after疑似要素で作成していますが、デザインやタグ構成なども自由に変更してもらえたらと思います。

.year_selector {
    position: relative;
    width: 180px;
    margin-bottom: 25px;
}

.year_selector select {
    /* セレクトボックスのデフォルトの矢印は非表示 */
    -webkit-appearance: none;  /* SafariとChrome */
    -moz-appearance: none;     /* Firefox */
    -ms-appearance: none;      /* Internet Explorer */
    appearance: none;          /* 標準 */
    background: #fff;
    border: 1px solid #CDD6DD;
    padding: 5px 15px;
    width: 100%;
    height: 50px;
    display: flex;
    align-items: center;
    color: #3B4043;
    font-size: 16px;
}

.year_selector_btn {
    position: absolute;
    right: 0;
    top: 0;
    width: 40px;
    height: 100%;
    display: flex;
    flex-direction: column;
}

.year_selector button {
    background-color: transparent;
    outline: none;
    border: none;
    width: 100%;
    display: block;
    position: relative;
    transition: transform 0.3s;
    flex: 1;
    cursor: pointer;
}

.year_selector button::after {
    content: "";
    display: block;
    border-right:2px solid #98A6B5;
    border-bottom: 2px solid #98A6B5;
    width: 5px;
    height: 5px;
    transform: translate(-50%,-50%) rotate(45deg);
    position: absolute;
    top: 29%;
    left: 50%;
    transition: transform 0.3s;
}

#year_decrease::after {
    top: 73%;
    transform: translate(-50%,-50%) rotate(-135deg);
}

JavaScript

肝心のJavaSctiptです。

まず、Selectボックスとボタンの要素を取得します。これらの要素に対して、クリックイベントリスナーを設定します。

yearIncreaseボタンのクリックイベントでは、selectedIndexプロパティを使って現在選択されている年のインデックスを取得し、選択肢の最後でない場合にインデックスを1増やします。これにより、次の年が選択されます。

同様に、yearDecreaseボタンのクリックイベントでは、現在選択されている年のインデックスを取得し、選択肢の最初でない場合にインデックスを1減らします。これにより、前の年が選択されます。

document.addEventListener('DOMContentLoaded', function() {

    // セレクトボックスと、操作するボタン要素を取得
    var yearSelect = document.getElementById('year_select');
    var yearIncrease = document.getElementById('year_increase');
    var yearDecrease = document.getElementById('year_decrease');

    // 年を増やすボタンのクリックイベント
    yearIncrease.addEventListener('click', function() {
        var selectedIndex = yearSelect.selectedIndex; // 現在選択されているインデックス取得
        // 選択されている年がリストの最後でない場合
        if (selectedIndex < yearSelect.options.length - 1) {
            yearSelect.selectedIndex = selectedIndex + 1; // 選択を次の年に移動
        }
    });

    // 年を減らすボタンのクリックイベント
    yearDecrease.addEventListener('click', function() {
        var selectedIndex = yearSelect.selectedIndex; // 現在選択されているインデックス取得
        // 選択されている年がリストの最初でない場合
        if (selectedIndex > 0) {
            yearSelect.selectedIndex = selectedIndex - 1; // 選択を前の年に移動
        }
    });
});

まとめ

このサンプルコードでは、HTML、CSS、JavaScriptを組み合わせて、Selectボックス内の年をボタンで動的に切り替える方法を紹介しました。
これにより、ユーザーが年を簡単に選択できるようになります。ぜひ、あなたのプロジェクトに活用してみてください。

-スニペット
-, ,