JavaScript onchangeを使用してチェックされたらvalue値を取得する
環境
Windows 10 Home 64bit
Google Chrome 106.0.5249.119
構文
1.onchangeのイベントハンドラの定義
onchange= '関数名(this.value)’
2.チェックボックス要素の取得
const 変数名 = document.getElementById(セレクターid名);
3.チェックされたかどうか判定
if(変数名.checked)
使用例
<!DOCTYPE html>
<html>
<body>
<p>選択値: <span id="show"></span></p>
<label><input type="checkbox" id="city" value="tokyo" onchange="funA(this.value)"/>東京</label>
<script>
// onchangeのイベントハンドラ
function funA(val) {
//チェックボックス要素の取得
const city = document.getElementById("city");
const shw = document.getElementById("show");
if (city.checked) {
// 取得したvalue値を画面に表示
shw.textContent = val;
} else {
shw.textContent = "";
}
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<p>選択値: <span id="show"></span></p>
<label><input type="checkbox" id="city" value="tokyo" onchange="funA(this.value)"/>東京</label>
<script>
// onchangeのイベントハンドラ
function funA(val) {
//チェックボックス要素の取得
const city = document.getElementById("city");
const shw = document.getElementById("show");
if (city.checked) {
// 取得したvalue値を画面に表示
shw.textContent = val;
} else {
shw.textContent = "";
}
}
</script>
</body>
</html>
<!DOCTYPE html> <html> <body> <p>選択値: <span id="show"></span></p> <label><input type="checkbox" id="city" value="tokyo" onchange="funA(this.value)"/>東京</label> <script> // onchangeのイベントハンドラ function funA(val) { //チェックボックス要素の取得 const city = document.getElementById("city"); const shw = document.getElementById("show"); if (city.checked) { // 取得したvalue値を画面に表示 shw.textContent = val; } else { shw.textContent = ""; } } </script> </body> </html>
結果
チェックボックスがチェックされたら「選択値: tokyo」が表示されます。