javascript セレクトボックスで選択されたテキストデータを取得する
- 2020.09.11
- javascript
- javascript

javascriptで、セレクトボックスで選択されたテキストデータを取得するサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 84.0.4147.105
テキスト取得方法
インデックス番号を指定してtextメソッドを使うと、セレクトボックスで選択したテキストを取得することが可能です。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
/* html部 */ <select id="select"> <option value="a">One</option> <option value="b">Two</option> <option value="c">Three</option> </select> /* js部 */ var obj = document.getElementById('select'); // 選択されている値の番号を取得 var idx = obj.selectedIndex; // 値を取得 var txt = obj.options[idx].text; |
サンプルコード
以下は、
「取得」ボタンをクリックすることで、選択したセレクトボックスのテキストを取得して、表示する
サンプルコードとなります。
※cssには「bootstrap material」を使用してます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>mebeeサンプル</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons"> <link rel="stylesheet" href="https://unpkg.com/bootstrap-material-design@4.1.1/dist/css/bootstrap-material-design.min.css" integrity="sha384-wXznGJNEXNG1NFsbm0ugrLFMQPWswR3lds2VeinahP8N0zJw9VWSopbjv2x7WCvX" crossorigin="anonymous"> </head> <style> .main { margin: 0 auto; margin-top: 200px; display: flex; flex-direction: column; align-items: center; font-size: 25px; width: 500px; } </style> <script> function hoge() { var obj = document.getElementById('select'); // 選択されている値の番号を取得 var idx = obj.selectedIndex; // 値を取得 var txt = obj.options[idx].text; // 表示 document.getElementsByClassName('badge-primary')[0].textContent = txt; } </script> <body> <div class="main"> <h2><span class="badge badge-primary">選択したテキスト</span></h2> <form> <div class="form-row align-items-center"> <div class="col-auto my-1"> <select id="select" class="custom-select mr-sm-2"> <option value="a">One</option> <option value="b">Two</option> <option value="c">Three</option> </select> </div> </div> </form> <button onclick="hoge();" type="button" class="btn btn-outline-warning">取得</button> </div> </body> </html> |
セレクトボックスのテキストが取得されていることが確認できます。

-
前の記事
javascript オブジェクトの要素を削除する 2020.09.11
-
次の記事
windows ディスクトップに白い枠が残って消えない 2020.09.12
コメントを書く