1-1. name 속성이 동일한 요소들끼리 하나의 배열로 그룹화 됨
var foo = document.form1.myradio[0].value;
<form id="myform">
<label><input type="radio" name="subject" value="html" />HTML</label>
<label><input type="radio" name="subject" value="css" />CSS</label>
<label><input type="radio" name="subject" value="javascript" />JAVASCRIPT</label>
<button type="button" id="btn">입력값 확인</button>
</form>
1-2. checked
프로퍼티를 사용하여 선택 여부를 조회하거나 선택 상태를 강제 설정 할 수 있음.
var foo = document.form1.myradio[0].chekcked;
if (foo) {
... 선택된 경우의 처리 ...
}
document.form1.myradio[0].checked = true;
1-3. 배열이라는 특성 때문에 반복문을 통한 제어가 가능
var checkbox = document.form_name.checkbox_name;
var count = 0;
for (var i=0; i<checkbox.length; i++) {
if (checkbox[i].checked) {
count++;
}
}
02.checkbox 예제
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form id="myform">
<label><input type="checkbox" class="hobby" value="soccor">축구</label>
<label><input type="checkbox" class="hobby" value="basketball">농구</label>
<label><input type="checkbox" class="hobby" value="baseball">야구</label>
<button type="submit">입력값 확인</button>
</form>
<hr />
<p id="console"></p>
<script>
const checkbox = document.querySelectorAll(".hobby");
for (let i = 0; i < checkbox.length; i++) {
checkbox[i].addEventListener('change', e => {
document.querySelector("#console").innerHTML = e.currentTarget.value;
});
}
document.querySelector("#myform").addEventListener("submit", e => {
e.preventDefault();
const checkedItem = [];
for (let i = 0; i < checkbox.length; i++) {
if (checkbox[i].checked) {
checkedItem.push(checkbox[i].value);
}
}
document.querySelector("#console").innerHTML = checkedItem;
});
</script>
</body>
</html>
03. radio 예제
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form id="myform">
<label><input type="radio" name="subject" value="html" />HTML</label>
<label><input type="radio" name="subject" value="css" />CSS</label>
<label><input type="radio" name="subject" value="javascript" />JAVASCRIPT</label>
<button type="button" id="btn">입력값 확인</button>
</form>
<hr />
<p id="console"></p>
<script>
const radio = document.querySelectorAll("input[name='subject']");
console.log(radio);
radio.forEach((v, i) => {
console.log(v);
v.addEventListener("change", e => {
document.querySelector("#console").innerHTML = e.currentTarget.value;
});
});
document.querySelector("#btn").addEventListener("click", e => {
let find = false;
radio.forEach((v, i) => {
if (find) {
return;
}
if (v.checked) {
document.querySelector("#console").innerHTML = i + "번째 항목" + v.value + "이(가)선택됨";
find = true;
}
});
});
</script>
</body>
</html>
``