0
0

More than 1 year has passed since last update.

セレクトボックスで選択したテキスト情報を出力する

Last updated at Posted at 2022-02-23

このようなセレクトボックスとテキストボックスがあったとする
スクリーンショット 2022-02-24 0.43.15.jpg
セレクトボックスの中身はこう
スクリーンショット 2022-02-24 0.44.13.jpg

htmlソースは以下

hanninsagashi.html
<div>犯人
    <select name='hannin' id='hannin'>
        <option value="1">本人</option>
        <option value="2"></option>
        <option value="3"></option>
        <option value="4">その他家族</option>
        <option value="5">該当なし</option>
  </select>
</div>
<div>
    <td>
    <textarea name="memo" id="memo" style="height: 50px; width: 150px"></textarea>
    </td>
</div>

セレクトボックスで選択した結果のテキスト情報をtextareaに出力させたい場合、
セレクトボックスで選択したvalueのindex値をselectedIndexを使用して取得した上で
textContentで出力するという方法でいける

purintabetadaro.js
const shinhannin = () => {
    const hannin = document.getElementById("hannin");
    const memo = document.getElementById("memo");
    const hanninIndex = hannin.selectedIndex;
    memo.value = hannin.options[hanninIndex].textContent;
}
document.getElementById("hannin").onchange = shinhannin;

このようにセレクトボックスのプルダウンのテキストがそのまま出てくれる
スクリーンショット 2022-02-24 0.48.20.jpg

セレクトボックスをJavascriptのオブジェクト的に表現した場合、以下になるということを
念頭に置いたらわかりやすいかもしれない

{value : 1 , name : "本人"}, //index : 0
{value : 2 , name : "夫"}, //index : 1
{value : 3 , name : "娘"}, //index : 2
{value : 4 , name : "その他家族"}, //index : 3
{value : 5 , name : "該当なし"} //index :4

つまり、夫(index値:1)を選択した場合、「document.getElementById("hannin").selectedIndex = 1」
ということになる
よって、「document.getElementById("hannin").options[1].textContent = 夫」
という結果になる

なお、「Cannot set property 'onchange' of null」が出た場合、
Javascriptの記述をHtmlの後に記述するなどの対処が必要

0
0
2

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
0
0