새벽코딩

[JavaScript기초] 8. form tag (with input tag) 본문

Programming/JavaScript

[JavaScript기초] 8. form tag (with input tag)

midnightcoder 2023. 2. 6. 12:55

이번 포스팅에서는 form 의 input tag 안에서 

1. input에 입력된 값을 get하는 방법

2. 그 값이 공백인 경우에 alert을 띄워주는 방법

3. 또한 값이 특정 길이 보다 짧을 경우에 alert을 띄워주는 방법을 알아 볼 예정이다.

 

아래와 같이 로그인을 위한 <form>을 생성 한 후

    <div class="black-bg">
        <div class="white-bg">
          <h4>로그인하세요</h4>
          <!-- 전송 누르면 action으로 지정된 url로 이동 -->
          <form action="sucess.html"> 
            <div class="my-3">
              <input type="text" class="form-control" id="email">
             </div>
             <div class="my-3">
               <input type="password" class="form-control" id="password">
             </div>
             <button type="submit" class="btn btn-primary" id="send">전송</button>
             <button type="button" class="btn btn-danger" id="close">닫기</button>
          </form> 
        </div>
      </div>

미리보기

 

1. input에 입력된 값을 어떻게 get할까?

 

먼저, 위에 첫번째 input field는 email을 입력하는 부분이고, 

해당 field에(id="email" 인 tag) 입력된 값이 무엇인지 아래와 같이 확인 할 수 있다.

document.getElementById('email').value
// id='email'인 요소의 value를 나타낸다

 

2. 입력값 (email 또는 password 입력값)이 공백일때 alert을 띄워주는 방법

 

3. 또한 password 값이 특정 길이(6) 보다 짧을 경우에 alert을 띄워주는 방법 (length를 이용)

 

아래 코드를 통해서 해답을 확인해보자

      <script>
        // 전송버튼 누르면 -> input에 입력한 값이 공백이면 alert 띄워주세요
        $('form').on('submit', function(e){
            if(document.getElementById('email').value == '' ||
            document.getElementById('password').value == ''
            ){
                alert('email and password should be entered!')
                e.preventDefault(); //form 전송을 막을 수 있다.
            }

            // the length of password is less than 7
            if(document.getElementById('password').value.length <  6){
                alert('The password cannot be less than 6.');
                e.preventDefault();
            }
        })

      </script>

 

여기서 첫번째 if문을 보게되면

둘중 하나라도 공백이라면 ▶  이 조건은 또는 (or) 조건으로 연산자 ( || 를 사용하였다)

 

그리고 두번째 if문을 보게되면

e.preventDafault() 라는 함수를 사용하여, form전송이 되지 않도록 막았다 (추후 포스팅예정)

 

비밀번호를 3자리 입력하였을때, 잘 작동한다.

 

출처 : 코딩애플 'JavaScript 입문과 웹 UI개발'