일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
- 영어
- npm 에러
- 실행컨텍스트콜스택
- CLI
- Mini Node Server
- 실행컨텍스트스택
- .env
- 실행컨텍스트 면접
- 로컬상태
- Block
- 전역상태
- html
- 개발일기
- css
- 알고리즘
- 객체
- styled-component
- 영어공부
- state hook
- 실행컨텍스트 실행과정
- .current
- 실행컨텍스트란
- 고차함수
- 실행컨텍스트자바스크립트
- CORS
- 실행컨텍스트 동작과정
- useRef역할
- 그래머인유즈
- 노마드코더
- 개발공부
- Today
- Total
오늘도 삽질중
로그인하기 submit event.preventDefault() 본문
로그인 화면을 만드는 여정을 떠나보자!
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이지! 라는 생각에 안도감이 든다 ㅎㅎ
'개발공부' 카테고리의 다른 글
Create React App(리액트 프로젝트 만들기) (0) | 2021.09.15 |
---|---|
Local Storage(setItem, getItem, removeItem) (2) | 2021.07.06 |
로그인2 (getting username) (0) | 2021.07.05 |
toggle로 가는 여정(toggle, classList, className) (4) | 2021.06.28 |