728x90
반응형
실행 화면
![]() |
![]() |
1. 스스로 작성한 코드( >> 선택값이 null 일때 작동안됨)
<!DOCTYPE html>
<html><head><meta charset="UTF-8">
<title>x</title>
</head>
<body>
<h3>선택된 라디오 버튼 알아내기</h3>
<hr>
<form>
<input type="radio" name="city" value="seoul">서울
<input type="radio" name="city" value="busan">부산
<input type="radio" name="city" value="chunchen">춘천
<button onclick="findChecked()">find checked</button>
</form>
<script>
function findChecked() {
var kcity = document.getElementsByName("city");
for(var i=0; i<kcity.length; i++) {
if (kcity[i].checked) return alert(kcity[i].value + "이 선택되었음");
}
}
</script>
</body>
</html>
2. 답안
<!DOCTYPE html>
<html><head><meta charset="UTF-8">
<title>x</title>
</head>
<body>
<h3>선택된 라디오 버튼 알아내기</h3>
<hr>
<form>
<input type="radio" name="city" value="seoul">서울
<input type="radio" name="city" value="busan">부산
<input type="radio" name="city" value="chunchen">춘천
<button onclick="findChecked()">find checked</button>
</form>
<script>
function findChecked() {
var found = null;
var kcity = document.getElementsByName("city");
for(var i=0; i<kcity.length; i++) {
if (kcity[i].checked) found = kcity[i];
}
if(found != null) alert(found.value + "이 선택되었음");
else alert("미선택");
}
</script>
</body>
</html>
'웹개발' 카테고리의 다른 글
[명품 웹 프로그래밍] 9장 예제 9-19, select 객체에서 선택한 과일 출력 (0) | 2021.12.12 |
---|---|
[명품 웹 프로그래밍] 9장 예제 9-18, 체크박스로 선택 물품 계산 (0) | 2021.12.12 |
[명품 웹 프로그래밍] 9장 예제 9-15, new Image()로 이미지 로딩 (0) | 2021.12.12 |
[명품 웹 프로그래밍] 9장 예제 9-14, onload로 이미지 크기 알아내기 (0) | 2021.12.11 |
[명품 웹 프로그래밍] 8장 실습문제 9, 라면 끓이는 순서 입력받기 (0) | 2021.12.11 |