JavaScript/4. 이벤트 기초 및 활용

Day 48 : 폼과 이벤트 활용

pancakemaker 2021. 12. 23. 11:16

1. onfocus와 onblur

: 포커스(focus)가 변경될 때 호출 - 포커스는 키 입력에 대한 독점권

- onfocus : HTML 요소가 포커스를 받게될 때 호출되는 리스너

- onblur : 포커스를 잃는 요소에 호출되는 리스너

 

<예시>

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>onfocus와 onblur</title>
	<script>
		function checkFilled(obj) {
			if(obj.value == "") {	//해당 태그 내부가 공백이면(입력되지 않으면)
				alert("enter name!");
				obj.focus(); 		//obj에 다시 포커스
			}
		}
	</script>
</head>
<body onload="document.getElementById('name').focus();">	<!-- 웹페이지가 로딩된 후 name 아이디를 가진 태그에 focus -->
	<h3>onfocus와 onblur</h3>
	<hr>
	<p>이름을 입력하지 않고 다른 창으로 이동할 수 없습니다.</p>
	<form>
		이름 <input type="text" id="name" onblur="checkFilled(this)"><p>		<!-- 해당 태그에서 focus를 벗어났을 때(onblur) checkFilled 함수 호출하여 검사 -->
		학번 <input type="text">
	</form>
</body>
</html>


2. 라디오버튼과 체크박스

① 라디오버튼 객체

: <input type="radio">로 만들어진 라디오버튼을 나타내는 DOM 객체

: radio 객체들은 하나의 그룹을 이루며 하나만 체크 가능 → name 지정하여 사용

 

② 선택된 라디오버튼 알아내기

: radio 객체의 checked 프로퍼티를 조사

 

<예시>

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>선택된 라디오버튼 알아내기</title>
	<script>
		function findChecked() {
			var found = null;
			var kcity = document.getElementsByName("city"); 	//각 radio 태그들을 kcity 배열에 저장
			for(var i=0; i<kcity.length; i++) {
				if(kcity[i].checked == true){					//각 radio 태그를 검사해서 checked 속성이 존재하면
					found = kcity[i];							//해당 태그를 found 변수에 저장
				}
			}
			if(found != null) {									//해당 태그가 null이 아니면 (radio 태그에 checked 속성이 있는 것이 존재하면)
				alert(found.value + "이 선택되었음");				//해당 태그의 value 속성값을 불러옴
			} else {
				alert("선택된 것이 없음");
			}
		}
	</script>
</head>
<body>
	<h3>버튼을 클릭하면 선택된 라디오버튼의 value를 출력합니다.</h3>
	<hr>
	<form>
		<input type="radio" name="city" value="seoul" checked>서울	<!-- 초기 선택값 -->
		<input type="radio" name="city" value="busan">부산
		<input type="radio" name="city" value="chuncheon">춘천
		<input type="button" value="find checked" onclick="findChecked()">
	</form>
</body>
</html>

③ 체크박스 객체

: <input type="checkbox">로 만들어진 체크박스를 나타내는 DOM 객체

: checkbox 객체들은 그룹을 이루지 않으며 여러 개 체크 가능

 

<예시>

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>선택한 물품 계산하기</title>
	<script>
		var sum = 0;
		function calc(cBox) {
			if(cBox.checked) {	//if(cBox.checked == true) 와 동일 - 체크박스 태그 속성 중 checked가 존재한다면
				sum += parseInt(cBox.value);	//해당 체크박스의 value들을 Int값으로 변경하여 sum 변수에 누적
			} else {
				sum -= parseInt(cBox.value);	//해당 체크박스의 checked 속성이 사라지면 sum 변수에서 차감
			}
			document.getElementById("sumtext").value = sum;	//sumtext 아이디를 가진 text박스의 value 속성값을 0으로 초기화 해놓았음
		}
	</script>
</head>
<body>
	<h3>물품을 선택하면 금액이 자동 계산됩니다.</h3>
	<hr>
	<form>
		<input type="checkbox" name="hat" value="10000" onclick="calc(this)">모자 1만원
		<input type="checkbox" name="shoes" value="30000" onclick="calc(this)">구두 3만원
		<input type="checkbox" name="bag" value="80000" onclick="calc(this)">가방 8만원<br>
		지불하실 금액 <input type="text" id="sumtext" value="0">
	</form>
</body>
</html>


3. select 객체와 onchange

<select id="fruits">
    <option value="1">딸기</option>
    <option value="2" selected>바나나</option>
    <option value="3">사과</option>
</select>

① select 객체

: <select> 태그에 의해 만들어진 콤보박스

 

② option 객체

: <option> 태그로 표현되는 옵션 아이템

 

③ 선택된 옵션 알아내기 : selectedIndex

var sel = document.getElementById("fruits");
var index = sel.selectedIndex;	//index는 선택 상태의 옵션 인덱스. index는 0부터 시작

 

④ onchange 리스너

: select 객체에 다른 옵션이 선택되면 호출되는 리스너

 

<예시>

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>select 객체에서 선택한 과일 출력</title>
	<script>
		function drawImage() {
			var sel = document.getElementById("fruits");
			var img = document.getElementById("fruitimage");
			img.src = sel.options[sel.selectedIndex].value;		//select에서 selected된 option의 인덱스를 가져와 대입하여 그 인덱스의 value(번호) 값을 이미지 src로 사용 (checked 아님)
		}
	</script>
</head>
<body onload="drawImage()">	<!-- 로딩 직후 drawImage() 호출 (선택 상태인 것의 이미지를 로딩 직후부터 바로 출력) -->
	<h3>select 객체에서 선택한 과일 출력</h3>
	<hr>
	<form>
		<select id="fruits" onchange="drawImage()">	<!-- select의 다른 옵션 선택 시(onchange) drawImage() 호출-->
			<option value="media/strawberry.png">딸기</option>
			<option value="media/banana.png">바나나</option>
			<option value="media/apple.png">사과</option>
		</select>
		<img id="fruitimage" src="" alt="">
	</form>
</body>
</html>


4. 키 이벤트 : onkeydown, onkeypress, onkeyup

- onkeydown : 모든 키에 대해 키가 눌러지는 순간 호출
- onkeypress : <Enter>, <Space>, <Esc> 키와 문자키에 대해서만 키가 눌러지는 순간 추가 호출. 
		<F1>, <Shift>, <PgDn>, <Del>, <Ins> 등 문자키가 아닌 경우 호출되지 않음
- onkeyup : 모든 키에 대해 눌러진 키가 떼어지는 순간 호출

-표


5. onreset과 onsubmit

- onreset 리스너 : reset 버튼(<input type="reset">)이 클릭되어 폼을 초기화할 때 호출

- onsubmit 리스너 : submit 버튼(<input type="submit">)이 클릭되어 폼을 서버로 전송할 때 호출

 

<예시>

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>키 이벤트</title>
	<script>
		function whatKeyDown(e) {
			var str = "";
			var div = document.getElementById("div");
			div.innerHTML = ""; 		//div 객체 내용 초기화
			str += "e.key = " + e.key + "<br>";
			str += "e.code = " + e.code + "<br>";
			div.innerHTML = str; 		//div 객체에 HTML 문자열 출력
		
			/*
			if(e.altKey) {
				if(e.altlLeft) str += "왼쪽 ALT 키가 눌러졌습니다.";
				else str += "오른쪽 ALT 키가 눌러졌습니다.";
				str =+ "<br>";
			}
			if(e.shiftKey) {
				if(e.shiftLeft) str += "왼쪽 SHIFT 키가 눌러졌습니다.";
				else str += "오른쪽 SHIFT 키가 눌러졌습니다.";
				str =+ "<br>";
			}
			if(e.ctrlKey) {
				if(e.ctrlLeft) str += "왼쪽 CTRL 키가 눌러졌습니다.";
				else str += "오른쪽 CTRL 키가 눌러졌습니다.";
				str =+ "<br>";
			}
			str += String.fromCharCode(e.keyCode) + "키가 눌러졌습니다.";

			div.innerHTML = str;		//div 객체에 HTML 문자열 출력
			*/
		} 
	</script>
</head>
<body>
	<h3>키 리스너와 이벤트 객체의 프로퍼티</h3>
	<hr>
	텍스트 창에 키를 눌러보세요. Alt, Shift, Ctrl 키도 가능합니다. <br>
	<input type="text" id="text" onkeydown="whatKeyDown(event)">
	<div id="div" style="background-color: skyblue; width: 250px; height: 50px;">		
	</div>
</body>
</html>