JavaScript querySelectorAllメソッドを使ってラジオボタンの選択状態を取得する方法
環境
Windows 10 home 64bit
Google Chrome 107.0.5304.122(Official Build) (64 ビット)
書式
1.「name=city」を持つ全てのラジオボタンを取得します。
let 変数名 =document.querySelectorAll(“input[name=city]");
querySelectorAllメソッドを使って同じname属性を持つ全てのinput要素を取得します。
2.for…in文でループして選択状態を取得します。
for(let ele of 変数名)
ele.addEventListenter('change',function(){
if(this.checked){処理コード}
}
for(let ele of 変数名)
ele.addEventListenter('change',function(){
if(this.checked){処理コード}
}
for(let ele of 変数名) ele.addEventListenter('change',function(){ if(this.checked){処理コード} }
使用例
<!DOCTYPE html>
<html>
<head>
<script>
window.addEventListener('DOMContentLoaded', function(){
// 「name=city」を持つ全てのラジオボタンを取得
let cft = document.querySelectorAll("input[name=city]");
for(let ele of cft) {
ele.addEventListener('change',function(){
if( this.checked) {
console.log(this.value);
}
});
}
});
</script>
</head>
<body>
<form>
<label for="to"><input type="radio" id="to" name="city" value="tokyo">東京</label>
<label for="oo"><input type="radio" id="oo" name="city" value="oosaka">大阪</label>
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script>
window.addEventListener('DOMContentLoaded', function(){
// 「name=city」を持つ全てのラジオボタンを取得
let cft = document.querySelectorAll("input[name=city]");
for(let ele of cft) {
ele.addEventListener('change',function(){
if( this.checked) {
console.log(this.value);
}
});
}
});
</script>
</head>
<body>
<form>
<label for="to"><input type="radio" id="to" name="city" value="tokyo">東京</label>
<label for="oo"><input type="radio" id="oo" name="city" value="oosaka">大阪</label>
</form>
</body>
</html>
<!DOCTYPE html> <html> <head> <script> window.addEventListener('DOMContentLoaded', function(){ // 「name=city」を持つ全てのラジオボタンを取得 let cft = document.querySelectorAll("input[name=city]"); for(let ele of cft) { ele.addEventListener('change',function(){ if( this.checked) { console.log(this.value); } }); } }); </script> </head> <body> <form> <label for="to"><input type="radio" id="to" name="city" value="tokyo">東京</label> <label for="oo"><input type="radio" id="oo" name="city" value="oosaka">大阪</label> </form> </body> </html>
結果
ラジオボタン「東京」を選択すると、コンソールログに下記メッセージを出力します。
tokyp