Web/JavaScript

[JavaScript] Form 입력 값 처리

luk_hwkim 2023. 2. 4. 22:28

HTML에서는 Form 태그를 사용하여 그 안에서 Input값을 받아와 처리를 할 수 있는데

JavaScript코드에서 해당 값에 대한 세부처리를 해줄 수 있다.

 

1. Form 태그의 "onsubmit"을 사용하는 방법

form 의 "onsubmit"에 대입되는 값이 false이면 해당 url 또는 페이지로 전송되지 않고, true이면 전송되게 된다

따라서 따로 입력 문자열을 체크하는 함수를 따로 정의하여 "onsubmit"에서 호출해주면 된다.

            <form action="success.html" onsubmit="return confirmValid()">
                <h4>로그인하세요</h4>
                <div class="my-3">
                    <input type="text" class="form-control" id="identity">
                </div>
                <div class="my-3">
                    <input type="password" class="form-control" id="password">
                </div>
                <button type="submit" class="btn btn-primary">전송</button>
                <button type="button" class="btn btn-danger" id="close">닫기</button>
            </form>
        
        <script>
        function confirmValid(){
            // $('.form-control')[0].value or 
            // document.getElementById('identity').value or 
            // document.querySelector('#identity').value 등 다양한 방법으로 대체할 수도있음
            inputId = $('#identity').val();
            inputPwd =  $('password').val();
            if (inputId == "" || inputPwd == "") {
                alert('아이디 혹은 비밀번호 입력을 해주세요');
                return false;
            } else{
                return true;
            }
        }
        </script>

 

2. form의 이벤트 리스너를 사용하는 방법

form태그의 submit 이벤트리스너를 사용하여 콜백함수 내에서 예외 처리를 해주어도 된다.

콜백함수 내에서 문자열 체크 후 공백이면 preventDefault() 함수를 호출해주고 있는데 

해당 함수는 특정 이벤트의 기본동작이 발생하지 않도록 막아주는 코드이다.

            <form action="success.html">
                <h4>로그인하세요</h4>
                <div class="my-3">
                    <input type="text" class="form-control" id="identity">
                </div>
                <div class="my-3">
                    <input type="password" class="form-control" id="password">
                </div>
                <button type="submit" class="btn btn-primary">전송</button>
                <button type="button" class="btn btn-danger" id="close">닫기</button>
            </form>
            
       <script> 
       $('form').on('submit', function(e){
            // $('.form-control')[0].value or 
            // document.getElementById('identity').value or 
            // document.querySelector('#identity').value 등 다양한 방법으로 대체할 수도있음
            inputId = $('#identity').val(); 
            inputPwd =  $('password').val();
            if (inputId == "" || inputPwd == "") {
                alert('아이디 혹은 비밀번호 입력을 해주세요');
                e.preventDefault();
            }
        })
        </script>