> For the complete documentation index, see [llms.txt](https://wlrma-study.gitbook.io/js-study/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://wlrma-study.gitbook.io/js-study/do-it-javascript/09..md).

# 09. 폼과 자바스크립트

## 1. 폼 요소에 접근하는 여러 가지 방

* id값이나 class값을 사용해 폼 요소에 접근하기

&#x20;     id값이나 class값을 사용해 폼 요소에 접근하는 방법은 DOM의 다른 요소에 접근하는 것과 같습니다. querySelector()함수나 querySelectorAll() 함수를 사용해서 특정 id 값이나 class값을 가진 요소에 접근할 수 있습니다.

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

* name값을 사용해 폼 요소에 접근하기

&#x20;   폼 요소에 id나 class 속성이 없고 name속성만 있다면 name 식별자를 사용해 폼 요소에 접근할 수 도 있습니다. 이 방법을 사용하려면 \<form>태그에 name속성이 지정되어 있어야 하고, \<form>태그 안에 포함된 폼 요소에도 name속성이 있어야 합니다.&#x20;

```
<form name="ship">
			<fieldset>
				<legend> 배송 정보 </legend>								
				<ul>
					<li>
						<input type="checkbox" id="shippingInfo" name="shippingInfo">
						<label for="bill_info" class="check">주문 정보와 배송 정보가 같습니다</label>
					</li>
					<li>
						<label class="field" for="shippingName">이름 : </label>
						<input type="text" class="input-box" id="shippingName" name="shippingName">
```

* 폼 배열을 사용해 폼 요소에 접근하기

&#x20;   이 방법은 폼 요소에 id나 class속성도 없고 name속성도 없을 때 사용합니다.

## 2. 폼 요소에서 입력값 검증하기

값이 입력되었는지, 입력된 값이 정해진 조건에 맞는지 등을 검사하는 이 작업은 흔히 폼 밸리데이션이라고 불립니다.&#x20;

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

userId.onchage = 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();   // 비밀번호를 다시 입력할 수 있게 포커싱
			}
		}
```

<비밀번호의 길이를 확인하고 입력값이 같은지 확인하는 코드>

## 3. 다양한 폼 요소 다루

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

```
<select name="major" id="major" onchange="displaySelect()">
```

선택 목록\<select>에 접근하여 항목을 선택 할 수 있다.

* 선택 목록에서 사용자가 선택한 옵션 항목 찾아내기

&#x20;   선택 목록에 접근하면 배열 형태가 반환되는데, selectIndex속성이 있는 것을 알수있다. 이 속성 값을 살펴보면 사용자가 어떤 항목을 선택했는지도 알 수 있다.

* 라디오 버튼과 체크 상자에 접근하기

&#x20;   라디오 버튼은 여러개의 항목 중에서 하나의 항목만 선택할 수 있고, 체크 상잦는 여러 개 항목을 선택할 수 있다는 차이가 있다.

![라디오 버튼에 입력된 값을 확인할 수 있다.](/files/-LuqN-xFcKdmv4q7Ce-d)

&#x20;  체크상자는 서로 다른 name값을 가지고 있기 때문에 폼 이름 뒤에 체크 상자의 이름을 연결해서 접근할 수 있다.

![](/files/-LuqNEJw3Dc47Vki9Wub)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wlrma-study.gitbook.io/js-study/do-it-javascript/09..md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
