본문 바로가기
Front-End Study/[코딩 자율학습] HTML+CSS+JavaScript

12장_문서 객체 모델과 이벤트 다루기_2

by 코딩기 2023. 12. 10.
728x90

12.5 폼 조작하기

  • form 태그 선택하기
    forms 속성, name 속성 사용하기
<!-- forms 속성 : 개발자 도구 콘솔창에 document.forms 명령어를 통해 조회-->
<body>
	<form>
		<input type = "text">
	</form>
	<form>
		<input type = "text">
	</form>
</body>
<!-- console -->
document.forms
HTMLCollection(2) [...]

<!-- name 속성 : form 태그의 name을 통해 요소 노드 접근-->
<body>
	<form name = "frm1">
		<input type = "text">
	</form>
	<form name = "frm2">
		<input type = "text">
	</form>
</body>
<!-- console -->
document.frm1;
document.frm2;
  • 폼 요소 선택하기
    elements 속성, name 속성 사용하기
<!-- elements 속성 -->
<body>
	<form name = "frm1">
		<label for = "uname"></label>
		<input type = "text" id = "uname" name = "uname">
		<label for = "gender"></label>
		<select id = "gender" name = "gender">
		...
</body>
<!-- console -->
document.frm1.element[1];

<!-- name 속성 -->
<!-- console -->
document.frm1.uname;
  • 폼 요소의 입력값 다루기
<form name = "frm">
	<input type = "text" name = "id">
	<input type = "password" name = "pw">
	<input type = "textarea" name = "text">
</form>
<form>
	<label><input type = "checkbox" value = "orrange">오렌지</label>
	<label><input type = "checkbox" value = "apple">사과</label>
	<label><input type = "checkbox" value = "grape">포도</label>
</form>
<form>
	<label><input type = "radio" name = "fruits" value = "apple">사과</label>
	<label><input type = "radio" name = "fruits" value = "orrange">오렌지</label>
	<label><input type = "radio" name = "fruits" value = "grape">포도</label>
</form>
<form>
	<select>
		<option value = "apple">사과</option>
		<option value = "orrange">오렌지</option>
		<option value = "grape">포도</option>
	</select>
</form>
<form name = "frm">
	<input type = "file" name = "upload">
</form>
// 한줄 입력 요소 다루기
document.frm.id.value;
document.frm.pw.value; <!-- value 값의 확인을 통한 유효성 검증 -->

// 여러줄 입력 요소 다루기
document.frm.text.value;

//체크박스 다루기
const checkboxEls = document.querySelectorAll(["type = checkbox"]);
for(let i = 0; i < checkboxEls.length; i++){
	if(checkboxEls[i].checked === true)
		console.log(checkboxEls[i].value);
}

// 라디오 버튼 다루기
const radioEls = document.querySelectorAll(["type = radio"]);
for(let i = 0; i < radioEls.length; i++){
	if(radioEls[i].checked === true)
		console.log(radioEls[i].value);
}

// 콤보 박스 다루기
const optionEls = document.querySelectorAll(["option"]);
for(let i = 0; i < optionEls.length; i++){
	if(optionEls[i].checked === true)
		console.log(optionEls[i].value);
}

// 파일 업로드 요소 다루기
const filesObj = document.frm.opload.files;
console.log(filesObj);

12.6 이벤트 다루기

  • 이벤트 종류
    마우스 이벤트
이벤트 설명
onclick 마우스로 클릭 시 발생
ondblclick 마우스로 빠르게 두번 클릭 시 발생
onmouseover 마우스 포인터를 올릴 시 발생
onmouseout 마우스 포인터가 빠져나갈 시 발생
onmousemove 마우스 포인터가 움직이면 발생
onwheel 마우스 휠을 움직이면 발생

키보드 이벤트

이벤트 설명
onkeypress 키보드 버튼을 누르는 동안 발생
onkeydown 키보드 버튼을 누를 시 발생
onkeyup 키보드 버튼을 눌렀다 뗄 시 발생

포커스 이벤트

이벤트 설명
onfocus 요소에 포커스가 될 시 발생
onblur 요소가 포커스를 잃을 시 발생

폼 이벤트
onsubmit : 폼이 전송될 때 발생

리소스 이벤트
onload : 웹 브라우저 리소스 코드 종료 시 발생

  • 이벤트 등록하기
<!-- 인라인 방식 이벤트 등록 -->
<button onclick = "clickEvent()">클릭</button>
<script>
	function clickEvent() {
		alert("click");
	}
</script>

<!-- 프로퍼티 리스너 방식 이벤트 등록 -->
<button>클릭</button>
<script>
	const btnEl = document.querySelector("button");
	btnEl.onclick = function () {
		alert("click");
	}
</script> 
// 이벤트 리스너 등록
const btnEl = document.querySelector("button");
btnEl.addEventListener("click", function() {
	alert("button Click");
});

12. 7 이벤트 객체와 this

  • 이벤트 객체 사용하기
    이벤트 함수에 매개변수로 event 지정
- PointerEvent 객체 주요 속성
 clientX : 마우스 클릭 x좌표(수평 스크롤 포함X)
 clientY : 마우스 클릭 y좌표(수평 스크롤 포함X)
 pageX : 마우스 클릭 x좌표(수평 스크롤 포함O)
 pageY : 마우스 클릭 y좌표(수평 스크롤 포함O)
 screenX : 모니터 왼쪽 위 모서리 기준 마우스 클릭 x좌표
 screenY : 모니터 왼쪽 위 모서리 기준 마우스 클릭 y좌표

- KeyboardEvent 객체 주요 속성
 keyCode : 키보드로 누른 키의 유니코드 값 반환
 ctrlKey : Ctrl 키를 누를 시 true, 아닐 시 false 반환
 altKey : Alt 키를 누를 시 true, 아닐 시 false 반환
 shiftKey : Shift 키를 누를 시 true, 아닐 시 false 반환
  • 이벤트 취소하기
    a 태그, form 태그 같은 경우 기본적으로 클릭과 전송 이벤트가 적용된 상태
    preventDefault() 메서드 이용 -> 이벤트 취소 적용
// 기본 형식
<a href = "https://coding-woogi.tistory.com/">내 블로그 이동</a>
<script>
	const aEl = document.querySelector("a");
	aEl.addEventListener("clcik", function(e){
		e.preventDefault();
	})
</script>
  • this 키워드 사용하기
    이벤트 발생 요소 노드를 직관적으로 가리킴
<p>text-1</p>
<p>text-2</p>
<p>text-3</p>
const pEls = document.querySelectorAll("p");
pEls.forEach(el) => {
	el.addEventListener("click", function(){
		if(this.style.color === "red"){ // 해당 p 태그 클릭 시 색 변경
			this.style.color = "black";
		}else{
			this.style.color = "red";
		}
	})
}