JS

JS 이벤트 처리 - forms

ryeonng 2024. 8. 1. 09:17
시나리오 코드
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        ul {
            list-style: none;
        }
        li {
            display: flex;
            align-items: center;
            justify-content: space-around;
        }
        label {
            margin-right: 20px;
            margin-bottom: 4px;
        }
        .flex--container {
            display: flex;
            justify-content: center;
            margin: 100px;
        }
    </style>
</head>
<body>
    <div class="flex--container">
        <form action="" onsubmit="return false;">
            <fieldset>
                <legend>배송지 입력</legend>
                <ul>
                    <li>
                        <label for="userName1">이름 : </label>
                        <input type="text" class="input--box" name="name" id="userName1" value="홍길동">
                    </li>
                    <li>
                        <label for="tel1">연락처 : </label>
                        <input type="text" class="input--box" name="tel" id="tel1" value="010-1234-1234">
                    </li>
                </ul>
                <button type="button" onclick="check()">check</button>
            </fieldset>
        </form>

        <br>

        <form action="https://www.naver.com" onsubmit="return false;">
            <fieldset>
                <legend>배송지 입력2</legend>
                <ul>
                    <li>
                        <label for="userName2">이름 : </label>
                        <input type="text" class="input--box" name="name" value="">
                    </li>
                    <li>
                        <label for="tet2">연락처 : </label>
                        <input type="text" class="input--box" name="tel" value="">
                    </li>
                </ul>
                <button type="button" onclick="send()">send</button>
            </fieldset>
        </form>
    </div>
    <script>
        function check() {
            let form1 = document.forms[0];
            let form2 = window.document.forms[1];

            // 자바스크립트를 통해서 요소 복사 처리
            form2.elements["name"].value = form1.elements["name"].value;
            form2.elements["tel"].value = form1.elements["tel"].value;

            console.log("form1",form1)
        }

        function send() {
            // 유효성 검사가 전부 true라면, 
            if(validationForm() ) {
                // form에 submit() 메서드를 호출하면 자바스크립트에서 서버 측으로 제출할 수 있다.
                document.forms[1].submit();
            }
        }

        function validationForm() {
            let form2 = document.forms[1];
            let name = form2.elements["name"].value;
            let tel = form2.elements["tel"].value;
            
            let isOk = true;
            // console.log("name",name);
            // console.log("tel",tel);
            console.log(typeof name);
            console.log(typeof tel);
            if(name != null) {
                alert("이름을 입력하세요");
                isOk = false;
                return false;
            }

            if(tel != null) {
                alert("연락처를 입력하세요");
                isOk = false;
                return false;
            }

            // 정규표현식 (숫자가 맞는지, 010으로 시작 하는지)

            if(tel.length < 3 ) {
                alert("올바른 연락처를 입력하세요.");
                isOk = false;
                return ;
            }

            // if else 문 - false
            return isOk;
        }

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

 

1. 문서에서 form에 접근하는 방법 

  • JavaScript에서는 document.forms 를 통해 페이지 내의 모든 폼 요소에 접근할 수 있다. 이는 HTMLFormElement의 HTMLCollection이다. 예를 들어, document.forms[0]은 페이지내의 첫 번째 폼 요소에 접근하고, document.forms[1]은 두 번째 폼 요소에 접근한다.
  • 폼 내의 입력 요소에 접근하기 위해 elements 속성을 사용할 수 있다. 예 : document.forms[0].element["name"]는 첫 번째 폼의 name 속성을 가진 입력 요소에 접근한다.

2. onsubmit에 대한 이해

  • onsubmit 이벤트는 폼이 제출될 때 발생한다.
  • 폼의 onsubmit 속성에 "return false;"를 설정하면, 폼이 실제로 제출되지 않는다. 이는 페이지가 새로고침되는 것을 방지한다. 일반적으로, 이 방법은 JavaScript를 통해 추가 유효성 검사를 수행하거나 AJAX를 사용하여 폼 데이터를 제출할 때 유용하다.

3. validation에 대한 이해

  • 유효성 검사(validation)는 사용자가 입력한 데이터가 올바른 형식인지 확인하는 과정이다.
  • JavaScript에서는 유효성 검사를 수행하여 사용자에게 오류 메시지를 표시하거나, 올바른 데이터만 서버로 전송할 수 있다.
  • 예제에서는 validationForm() 함수가 유효성 검사를 수행한다. 이름이 비어 있거나, 연락처가 숫자가 아닌 경우 경고 메시지를 표시한다.

'JS' 카테고리의 다른 글

JS 이벤트 처리 - 이미지 토글  (0) 2024.08.02
JS 이벤트 처리 - 반복문과동적생성  (0) 2024.08.01
JS 이벤트 처리 - addEventListener  (0) 2024.07.26
JS 이벤트 처리 - 기본  (2) 2024.07.24
웹 페이지 렌더링 과정  (0) 2024.07.23