폼(Form) 요소 다루기

My Pale Blue Dot·2025년 2월 20일

JAVASCRIPT

목록 보기
16/26
post-thumbnail

📅 날짜: 2025-02-19

📚 학습 내용


🔹 2. 폼(Form) 요소 다루기

📌 개념 정리

HTML 폼 요소에 접근하고 조작하는 방법을 학습했다.

  • document.forms : 모든 <form> 요소를 가져옴
  • document.joinForm : name="joinForm"을 사용해 특정 폼 선택
  • formEl[0][0].value : 인덱스를 사용해 폼 내부 요소 접근 가능
  • 폼 요소의 값을 변경하는 방법 (.value 사용)

📌 코드 원본 (설명 포함)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form Handling</title>
</head>
<body>
    <!-- 폼이 여러 개 존재 -->
    <form action="">
        <input type="text">
        <input type="text">
    </form>
    <form action="" name="joinForm">
        <input type="text" name="userid">
        <input type="text" name="username">
    </form>
    <form action="">
        <input type="text">
        <input type="text">
    </form>

    <script>
        // ✅ 1. 모든 form 요소 찾기
        // document.forms를 사용하면 모든 form 요소를 가져올 수 있음
        const formEls = document.forms;
        console.log(formEls); // HTMLCollection 반환

        //------------------------------------------------------------

        // ✅ 2. 개별 form 접근 (인덱스 사용)
        console.log(formEls[0]); // 첫 번째 form
        console.log(formEls[1]); // 두 번째 form
        console.log(formEls[2]); // 세 번째 form

        //------------------------------------------------------------

        // ✅ 3. 특정 form 내부 요소 접근
        console.log(formEls[0][0]); // 첫 번째 form의 첫 번째 input
        console.log(formEls[0][1]); // 첫 번째 form의 두 번째 input

        // 첫 번째 form의 input 값을 설정
        formEls[0][0].value = '홍길동';
        formEls[0][1].value = '15';

        //------------------------------------------------------------

        console.log('--------------');

        // ✅ 4. name 속성으로 form 접근
        // name="joinForm"을 사용하여 해당 form을 직접 선택 가능
        const formEl = document.joinForm;

        // 특정 input 요소에 값 입력
        formEl.userid.value = 'user1234';
        formEl.username.value = '티모';

    </script>
</body>
</html>

📌 코드 실행 흐름 분석

1️⃣ 모든 폼 요소 찾기 (document.forms)

const formEls = document.forms;
console.log(formEls);

document.formsHTML 문서 내 모든 <form> 요소를 HTMLCollection으로 반환


2️⃣ 개별 폼 접근 (인덱스 사용)

console.log(formEls[0]); // 첫 번째 폼
console.log(formEls[1]); // 두 번째 폼
console.log(formEls[2]); // 세 번째 폼

formEls[0]으로 첫 번째 <form>을 선택하여 직접 접근 가능


3️⃣ 특정 폼 내부 요소 접근

console.log(formEls[0][0]); // 첫 번째 input 요소
console.log(formEls[0][1]); // 두 번째 input 요소

// 첫 번째 input 값 변경
formEls[0][0].value = '홍길동';
formEls[0][1].value = '15';

formEls[0][0]을 사용하여 첫 번째 폼의 첫 번째 input 요소를 직접 변경


4️⃣ name 속성을 사용하여 특정 폼 선택

const formEl = document.joinForm;
formEl.userid.value = 'user1234';
formEl.username.value = '티모';

document.joinForm을 사용하면 name="joinForm"을 가진 폼에 직접 접근 가능
🚀 보다 직관적인 코드 작성 가능!


📌 최종 요약

학습 내용주요 개념
폼 요소 선택document.forms, name 속성을 이용한 접근
폼 내부 요소 선택formEl[0][0] (인덱스를 사용한 접근)
폼 값 변경.value 속성을 이용한 값 설정
profile
Here, My Pale Blue.🌏

0개의 댓글