【JavaScript】セレクトボックスの要素を選択・取得・追加する方法!

JavaScript

今回は、JavaScriptでセレクトボックスの要素を選択取得追加削除する方法を説明します!

セレクトボックスの要素を選択

<select name='sns' id="sns">
  <option value='0'>YouTube</option>
  <option value='1' selected>X</option>
  <option value='2'>Instagram</option>
  <option value='3'>TikTok</option>
</select>

セレクトボックスにデフォルトの選択状態を設定するには、optionタグにselectedを設定します。jsでセレクトボックスの要素を選択させるには、valueを変更する方法selectedtrueにする方法があります。

valueを変更する

下記のコードではボタンをクリックすると、セレクトボックスのvalueを変更するようにしています。

<script>
  document.getElementById("selectedSns").addEventListener("click", function() {
       // 選択状態を変更
    document.getElementById("sns").value = "3";
    });
</script>

selectedをtrueにする

下記のコードは、「valueを変更する」方法と同じようにボタンをクリックして選択状態を変更していますが、option[value=’2′] を選択状態にするために selected = true を設定しています。 

<script>
  document.getElementById("selectedSns").addEventListener("click", function() {
       // 選択状態を変更
    document.querySelector("#sns option[value='2']").selected = true;
    });
</script>

セレクトボックスの要素を取得

次はセレクトボックスの要素の取得についてです。

セレクトボックスで選択された値を取得するには、セレクトボックスのId.valueで取得することができます。またテキストを取得するにはId.options[Id.selectedIndex].textで取得することができます。

// セレクトボックスのIdを取得
let selectBox = document.getElementById("sns");
// 値の取得
let selectedValue = selectBox.value; 
// テキストの取得
let selectedText = selectBox.options[selectBox.selectedIndex].text;

セレクトボックスの要素を追加・削除

セレクトボックスの値を追加するには「セレクトボックスのId.appendChild.(新しいoption要素)」、削除するには「セレクトボックスのId.remove(Id.selectedIndex)」です。

HTML
<label for="textInput"></label>
<input type="text" id="textInput" placeholder="値を入力してください">
<select id="sample"></select>
<button id="addOption">追加</button>
<button id="removeOption">削除</button>
JavaScript
<script>
    document.getElementById("addOption").addEventListener("click", function() {
        let textInput = document.getElementById("textInput").value.trim(); // 入力値を取得&前後の空白を削除
        let selectBox = document.getElementById("sample");
     // 入力チェック
        if (textInput === "") {
            alert("追加する値を入力してください!");
            return;
        }
        // 新しい option 要素を作成
        let newOption = document.createElement("option");
        newOption.text = textInput;
        newOption.value = textInput; // value もテキストと同じに設定
        selectBox.appendChild(newOption); // セレクトボックスに追加
        document.getElementById("textInput").value = ""; // 入力欄をクリア
    });
    document.getElementById("removeOption").addEventListener("click", function() {
        let selectBox = document.getElementById("sample");
        // 入力チェック
        if (selectBox.selectedIndex === -1) {
            alert("削除する値を選択してください!");
            return;
        }
        selectBox.remove(selectBox.selectedIndex); // 選択された値を削除
    });
</script>

まとめ

セレクトボックスの要素を操作するには、セレクトボックスのIdを取得しId.valueId.textでセレクトボックスの値が取得できることを覚えておきましょう!

コメント

タイトルとURLをコピーしました