오늘도 삽질중

로그인하기 submit event.preventDefault() 본문

개발공부

로그인하기 submit event.preventDefault()

해빋 2021. 6. 30. 00:43

로그인 화면을 만드는 여정을 떠나보자!

 

 

 html

1
2
3
4
5
6
7
8
<body>
<form id="login-form">
    <input required max-length="15" type="text" placeholder="what is your name?">
    <button>log In</button>
</form>
 
    <script src="app.js"></script>
</body>
cs

 

js

1
2
3
4
5
6
7
8
9
10
11
 const loginForm = document.querySelector("#login-form");
 const loginInput = document.querySelector("#login-form input");
 const loginButton = document.querySelector("#login-form button");
 
 function onLoginBtnClick(){
             
         console.log(loginInput.value);
 }
 
 
 loginForm.addEventListener("submit",onLoginBtnClick);
cs

 

cf) submit은 엔터를 누르거나 버튼을 클릭할 때 발생한다. submit 기본동작에 새로고침이 포함되어있다. 

 

이렇게하고 텍스트 입력후 버튼을 눌러 콘솔을 살펴보니,, value가 번쩍하더니 사라졌고 html에서도 텍스트 초기화가 되었다.

텍스트가 초기화되면 입력한게 무슨 소용인가...

깨달은사실 => submit event감지 성공. 근데 submit의 기본동작인 '새로고침'이 작동이되는데 이걸  멈추게해야 한다.

 

 

어떤 event의 기본 동작이 발생되지 않도록 막는 코드==> event.preventDefault( )

 

 

js

1
2
3
4
5
6
7
8
9
10
11
12
13
 const loginForm = document.querySelector("#login-form");
 const loginInput = document.querySelector("#login-form input");
 const loginButton = document.querySelector("#login-form button");
 
 function onLoginBtnClick(blueberry){
     
    blueberry.preventDefault();
    console.log(loginInput.value);
   console.log(blueberry);
                 
 }
 
 
 loginForm.addEventListener("submit",onLoginBtnClick);
cs

js는 단순히 함수를 실행시키기만 하는게 아니라, 함수를 실행시키는 동시에 그 함수의 첫 번째 argument로 event object를 준다. 공간만 제공을하면 js가 알아서 방금 일어난 submit event에 대한 정보를 첫 번째 argument에  눌러담아 줄거다. 참고로 submit event 에 관한 정보는 console.log(blueberry)를 통해 볼 수 있다. 나는 오늘 blueberry를 먹어서 argument를 blueberry로 줬다^^ 공간만 제공하면되는거니까 아무거나 써도 상관없음 ㅎㅎ 

아무튼 event object를 blueberry(argument)로 주고있고 blueberry.preventDefault();를 해주면

기본동작 실행이 중지된다.

 

 

 

끝! 

 

 

 

 

 

 

 

내가 이해한거 적은건데.. 틀리면 어쩌지?하는 생각이 들었던 찰나..유입이 0이지! 라는 생각에 안도감이 든다 ㅎㅎ

 

 

 

 

 

 

Comments