Notice
Recent Comments
Recent Posts
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
Today
Total
관리 메뉴

기록 > 기억

[JavaScript] 폼 객체 ③ checkbox 객체 본문

IT국비지원

[JavaScript] 폼 객체 ③ checkbox 객체

BY SON 2021. 9. 29. 09:35

checkbox 객체

 

예제 ①

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>form - select</title>
<script>
	let member = ["홍길동", "남자"];
	let hobby = ["축구", "농구", "탁구"];
	let frm;
	let flag;
	let out;
	
	window.onload = function() {
		frm = document.frm_member;
		out = document.getElementById("output");
		
		initData();
		
		frm.onchange = changedData;
		frm.btnModify.onclick = updateData;	
		frm.btnPrint.onclick = printData;	
	}
	
	//데이터 초기값
	function initData() {
		
		frm.member.value = member[0];	//이름	
		
		if(frm.rdo[0].value == member[1]) {	//성별
			frm.rdo[0].checked = true;
		}else {
			frm.rdo[1].checked = true;
		}
		
		for(let i=0; i<hobby.length; i++) {	//취미
			for(let j=0; j<frm.chk.length; j++) {
				if(hobby[i] == frm.chk[j].value) {					
					frm.chk[j].checked = true;
					break;
				}
			}
		}//for end
		
		flag = true;
	}
	
	//폼 데이터 변경하면 반드시 수정버튼 눌러야함
	function changedData() {
		flag = false;
	}
	
	//수정한 값을 다시 배열에 넣기
	function updateData() {
		if(flag == true) {
			alert("데이터를 수정하지 않았습니다");
		}
		else {
			member[0] = frm.member.value;
			member[1] = frm.rdo.value;
			
			hobby.length = 0;
			for(let i=0; i<frm.chk.length; i++) {
				if(frm.chk[i].checked) {
					hobby.push(frm.chk[i].value);	
				}
			}
			alert("변경한 데이터를 성공적으로 저장하였습니다");
			flag = true;
			printData();
		}
	}
	
	//수정한 값들 출력하기
	function printData() {
		if(flag == false) {
			alert("데이터를 변경하셨습니다\n수정 버튼을 눌러 데이터를 저장 해주세요");
		}else {
			let str = "";
			str += "<li>이름 : " + member[0] + "</li>"
			     + "<li>성별 : " + member[1] + "</li>"
			     + "<li>취미 : " + hobby + "</li>";			
			out.innerHTML = str;	
		}		
	}	
</script>
</head>
<body>
<div id="wrapper">
	<form name="frm_member" method="post">
		<h3>회원정보수정</h3>
		<label>성명</label>
		<input type="text" name="member"><br>
		<label>성별</label>
		<label><input type="radio" name="rdo" value="남자">남자</label>
		<label><input type="radio" name="rdo" value="여자">여자</label><br/>
		<label>취미</label>
		<label><input type="checkbox" name="chk" value="축구">축구</label>
		<label><input type="checkbox" name="chk" value="농구">농구</label>
		<label><input type="checkbox" name="chk" value="배구">배구</label>
		<label><input type="checkbox" name="chk" value="탁구">탁구</label>
		<label><input type="checkbox" name="chk" value="족구">족구</label>
		<label><input type="checkbox" name="chk" value="야구">야구</label><hr/>
		<input type="button" value="수정" id="btnModify">		
		<input type="button" value="출력" id="btnPrint">
		<div id="output"></div>		
	</form>
</div>
</body>
</html>

 

Comments