JavaScript フォーム名(form name)とセレクトボックス名で選択した値を取得する
環境
Windows 10 Home 64bit
Google Chrome 106.0.5249.119
構文
const 変数名 = document.フォーム名.セレクトボックス名;
セレクトボックスの数値(項目)の値を取得します
変数名.selectedIndex
選択された項目を取得します
変数名.options[項目のインデックス値].value
使用例
<!DOCTYPE html>
<html>
<body>
<p>選択都市名: <span id="show"></span></p>
<form name="frmcity">
<select name="city">
<option value="tokyo">東京</option>
<option value="oosaka">大阪</option>
<option value="fukuoka">福岡</option>
</select>
</form>
<p><input type="button" value="表示" onclick="funA()"/></p>
<script>
function funA(){
// セレクトボックス「city」の取得
const city = document.frmcity.city;
// セレクトボックスの数値(項目)の値を取得
const num = city.selectedIndex;
// 選択されている項目(数値)を取得
const result = city.options[num].value;
//フォームのshow要素に値を表示
document.getElementById("show").textContent = result;
}
</script>
</body>
</html>
結果
「福岡」を選択し、ボタン「表示」を押すと、「選択都市名: oosaka」が表示されます。