[DAY31-1]_개발일지: DOM 요소 추가 & Form

hanseungjune·2022년 6월 16일
0

DaeguFE

목록 보기
36/48

✅ DOM에 요소 추가하기

☑️ 새로운 노드를 만들거나 부모 노드에 연결할 때

  • createElement() : 새 요소 노드를 만듭니다.
  • createTextNode() : 텍스트 내용이 있을 경우 텍스트 노드를 만듭니다.
  • appendChild() : 텍스트 노드를 요소 노드에 자식 노드로 추가합니다.
  • createAttribute() : 요소에 속성이 있을 경우 속성 노드를 만듭니다.
  • setAttributeNode() : 속성 노드를 요소 노드에 연결합니다.
  • appendChild() : 새로 만든 요소 노드를 부모 노드에 추가합니다.

✅ 버튼에 이벤트 처리 함수 연결

<body>
  <div id = "container">
    <h1>참가 신청</h1>
    <form action = "">
    	<input type="text" id="userName" placeholder="이름" required>
     	<button onclick="newRegister(); return false;">신청</button>
    </form>
    <hr>
    <div id="nameList"></div>	//신청 명단이 표시될 영역
  </div>
</body>

✅ 노드 추가 & 표시

function newRegister() {
	var newP = document.createElement("p"); // 새 요소 만들기
  	var userName = document.querySelector("#userName"); 
  	var newText = documnet.createTextNode(userName.value); // 새 텍스트 노드 만들기
  	newP.appendChild(newText); // 텍스트 노드를 p 요소의 자식 요소로 연결하기
  
	var nameList = document.querySelector("#nameList"); 
  	nameList.appendChild(newP); // p요소를 #nameList의 자식 요소로 만들기
  	userName.value = ""; //텍스트 필드 지우기
}

☑️ hasChildNodes( ) 함수

  • 특정 노드에 자식 노드가 있는지 확인하는 함수. 자식 노드가 있다면 true, 없다면 false 반환

☑️ childNodes 속성

  • 현재 노드의 자식 노드를 가지고 있는 속성. 요소 노드 뿐만 아니라 빈 텍스트 노드도 자식으로 인식.

☑️ children 속성

  • 현재 노드의 자식 노드 중 요소 노드만 가지고 있는 속성

☑️ insertBefore( ) 함수

  • 부모 노드에 자식 노드를 추가할 때 기준 노드를 지정하고 그 앞에 자식 노드 추가

☑️ removeChild( ) 함수와 parentNode 속성

  • 노드는 스스로 자신을 삭제할 수 없기 때문에 부모 노드에 접근한 후 부모 노드에서 삭제해야 함.
  • parentNode 속성 – 현재 노드의 부모 노드 정보를 가지고 있는 속성
  • removeChild( ) 함수 - 부모 노드에서 자식 노드를 삭제하는 함수

✅ 노드 순서 바꾸기 & 삭제

var nameList = document.querySelector("#nameList");
nameList.insertBefore(newP, nameList.childNodes[0]); // p 요소를 #nameList 맨 앞에 추가하기
// nameList.appendChild(newP); // p 요소를 #nameList의 자식 요소로 만들기
userName.value = ""; // 텍스트 필드 지우기

var removeBttns = document.querySelectorAll(".del");

for ( var i=0 ; i < removeBttns.length ; i++ ) {  // removeBttns에 있는 요소 전체를 반복
	removeBttns[i].addEventListener("click", function() {  // i번째 버튼을 클릭했을 때 실행할 함수 선언
    	if (this.parentNode.parentNode)  // 현재 노드(this)의 부모 노드의 부모 노드가 있을 경우 실행
        	this.parendNode.parentNode.removeChild(this.parentNode);
      		// '현재 노드(this)의 부모 노드의 부모 노드'를 찾아 '현재 노드(this)의 부모 노드(p 노드)' 삭제
    });

}

✅ 배송 정보 자동 입력하기

  • 체크박스에 체크하면 입력한 주문 정보를 배송 정보에 자동 입력하기

☑️ 폼 요소에 접근하는 방법 - CSS 선택자 사용

HTML 문서

<label class="field" for="">이름 : </label>
<input type="text" class="input-box" id="billingName" name="billingName">

id 값을 사용해 접근해서 값 가져오기

document.querySelector("#billingName").value
// 한라산  //텍스트 필드에 입력한 값

☑️ 폼 요소에 접근하는 방법 – name 속성 사용

  • <form> 태그와 폼 요소에 모두 name 속성이 있어야 함

HTML 문서

<form name="ship">
	...
  <label class="field" for="shippingName">이름 : </label>
  <input type="text" class="input-box" id="shippingName" name="shippingName">
	...
</form>

name 속성을 사용해 접근해서 값 가져오기

document.ship.shippingName.value
// 도레미

☑️ 폼 요소에 접근하는 방법 – 배열 사용

  • css 선택자도 없고, name 속성도 없을 때 → form 배열 사용

HTML 문서

<form>
  <div id="login_input">
  	<input type="text" autofocus placeholder="아이디">
    <input type="password" placeholder="비밀번호">
  </div>
  <div id="login_bttn">
    <button type="submit" class="order">로그인</button>
  </div>
</form>

forms 배열

document.forms
// ▶ HTMLCollection [form]

아이디 입력하고 값에 접근하려면

document.forms[0].elements[0].value
// imHong // 1) 현재 문서의 2) 첫 번째 form의 3) 첫 번째 요소의 4) 값

☑️ 배송 정보 자동 입력하기

<li>
  <label class="field" for="billingName">이름 : </label>
  <input type="text" class="input-box" id="billingName" name="billingName">
</li>
<li>
  <label class="field" for="billingTel">연락처 : </label>
  <input type="text" class="input-box" id="billingTel" name="billingTel">
</li>
<li>
  <label class="field" for="billingAddr">주소 : </label>
  <input type="text" class="input-box" id="billingAddr" name="billingAddr">
</li>
...
<li>
  <label class="field" for="shippingName">이름 : </label>
  <input type="text" class="input-box" id="shippingName" name="shippingName">
</li>
<li>
  <label class="field" for="shippingTel">연락처 : </label>
  <input type="text" class="input-box" id="shippingTel" name="shippingTel">
</li>
<li>
  <label class="field" for="shippingAddr">주소 : </label>
  <input type="text" class="input-box" id="shippingAddr" name="shippingAddr">
</li>
var check = document.querySelector("#shippingInfo"); //체크 상자의 id는 shippingInfo

check.addEventListener("click", function() { //check 요소에 click 이벤트가 발생했을 때 실행할 함수
  if (check.checked == true) { //체크된다면
  	document.querySelector("#shippingName").value
    = document.querySelector("#billingName").value; // 주문 정보(이름)을 배송 정보(이름)에 복사
    document.querySelector("#shippingTel").value
    = document.querySelector("#billingTel").value; // 주문 정보(전화번호)을 배송 정보(전화번호)에 복사
    document.querySelector("#shippingAddr").value
    = document.querySelector("#billingAddr").value; // 주문 정보(주소)을 배송 정보(주소)에 복사
  }
  else {  //체크가 해제된다면 배송 정보 필드를 지움.
  	document.querySelector("#shippingName").value = "";
    document.querySelector("#shippingTel").value = "";
    document.querySelector("#shippingAddr").value = "";
  }
});

☑️ 폼 요소에서 아이디 글자 수 확인하기

var userId = document.querySelector("#user-id"); //'아이디' 필드를 가져와 변수에 저장

userId.onchange = checkId;

function checkId() {
	if(userId.value.length < 4 || userId.value.length > 15) { // userId 필드 내용의 길이가 4 이하이거나 15 이상 이라면,
    	alert("4~15 자리의 영문과 숫자를 사용하세요."); // 오류 메시지 출력
      	userId.select(); // 다시 입력할 수 있도록 userId 필드 선택
    }
}

☑️ 폼 요소에서 비밀번호 비교하기

var pw1 = document.querySelector("#user-pw1"); //'비밀번호' 필드를 가져와 변수에 저장
var pw2 = document.querySelector("#user-pw2"); //'비밀번호 확인' 필드를 가져와 변수에 저장

pw1.onchange = checkPw;
pw2.onchange = comparePw;

function checkPw() {
	if(pw1.value.length < 8){
    	alert("비밀번호 8자리 이상이어야 합니다."); //오류 메시지 표시
      	pw1.value = ""; // '비밀번호' 필드 지움
      	pw1.focus(); // 비밀번호를 다시 입력할 수 있게 포커싱
    }
}

function comparePw() {
 if(pw1.value != pw2.value){
 	alert("암호가 다릅니다. 다시 입력하세요.");
   	pw2.value = ""; // '비밀번호 확인' 필드 지움
   	pw2.focus(); // 비밀번호를 다시 입력할 수 있게 포커싱
 }
}

☑️ 선택 목록 및 옵션 항목에 접근하기

HTML 문서

<form name="testForm">
	...
  <label class="reg" for="class">학과</label>
  <select name="major" onchange="displaySelect()">
    <option>---학과 선택---</option>
  	...
  </select>
  	...
</form>

선택 목록 중 특정 옵션 항목 다루기

document.testForm.major.options[4]	//다섯 번째 옵션 항목에 접금
<option value="elec">전기전자공학과</option>

document.testForm.major.option[4].innerTexrt //다섯 번째 옵션 항목의 화면 표시 내용
// "전기전자공학과"

document.testForm.major.options[4].value //다섯 번째 옵션의 서버 전달 값
// "elec"

어떤 항목을 선택했는지 확인하기

  • selectedIndex 속성에 인덱스 값이 들어 있음

  <label class="reg" for="class">학과</label>
  <select name="major" onchange="displaySelect()">
    <option>---학과 선택---</option>
  	...
  </select>
var selectMenu = document.testForm.major; //선택 목록을 가져와 selectMenu로 저장

function displaySelect() {
	var selectedText = selectMenu.options[selectMenu.selectedIndex].innerText;
  // 선택한 옵션의 innerText를 가져와 selectedText에 저장
 	alert("[" + selectedText + "]를 선택했습니다."); //selectedText 내용을 알림 창에 표시
}

☑️ 라디오 버튼 & 체크 상자에 접근하기

  • 라디오 버튼과 체크 상자의 checked 속성
    기본값 false. 항목을 선택하면 값이 true로 바뀜
<form name="testForm">
  ...
  <legend>신청 과목</legend>
  <p>이 달에 신청할 과목을 선택하세요.</p>
  <label><input type="radio" name="subject" value="speaking">회화</label>
  <label><input type="radio" name="subject" value="grammar">문법</label>
  <label><input type="radio" name="subject" value="writing">작문</label>
  
  <legend>메일링</legend>
  <p>메일로 받고 싶은 뉴스 주제를 선택해 주세요</p>
  <label><input type="checkbox" name="mailing1" value="news">해외 단신</label>
  <label><input type="checkbox" name="mailing2" value="dialog">5분 회화</label>
  <label><input type="checkbox" name="mailing3" value="pops">모닝 팝스</label>
  • 라디오 버튼 중 [문법] 클릭하면
	document.testForm.subject[0].checked 	//false
	document.testForm.subject[1].checked	//true
	document.testForm.subject[2].checked	//false
  • 체크박스 버튼 중 [해외 단신] 클릭하면
	document.testForm.mailing1.checked 	//true
	document.testForm.mailing2.checked	//false
	document.testForm.mailing3.checked	//false

☑️ 태그 자체에서 폼 검증하기

<input> 태그의 새로운 유형

: 이메일 주소 필드입니다. 이메일 주소 형식에 맞지 않으면 오류 메시지를 표시합니다.
: 전화번호 필드입니다. 전화번호 숫자가 아닌 내용을 입력하면 오류 메시지를 표시합니다.
: 사이트 주소 필드입니다. http:로 시작하지 않으면 오류 메시지를 표시합니다.

<input> 태그의 새로운 속성

autocomplete : 자동 완성 기능을 켜고 끄는 속성입니다.
autofocus : 해당 필드에 마우스 커서를 자동으로 표시합니다.
placeholder : 필드 안에 힌트가 표시되어 사용자에게 어떤 내용을 입력해야 하는지 알려 줍니다. 필드 내부를 누르면 표시된 힌트가 사라집니다.
required : 필수 입력 항목으로 지정합니다. 필드가 작성하지 않으면 오류 메시지를 표시하며 다음 단계로 넘어갈 수 없습니다.

profile
필요하다면 공부하는 개발자, 한승준

0개의 댓글