주로 submit 동작에는 Form 데이터를 서버에 전송하고, <a href=””>와 같이 페이지 이동이 발생합니다.
예제 코드
HTML 코드 (Basic)
html<form id="form">
<input type="text" name="name" id="name" />
<button>로그인</button>
</form>
1. 모든 submit 동작 막기 (JavaScript)
javascriptconst $form = document.querySelecotr('form');
$form.addEventListener("submit", (event) => {
// 동작(이벤트)을 실행하지 못하게 막는 메서드입니다.
event.preventDefault();
console.log(event.target);
});
“event.preventDefault()”는 브라우저에 동작하는 이벤트를 실행하지 못하게 막아주는 메서드입니다.
해당 메서드로 submit 이벤트 감지는 되지만, Form을 전송하는 등의 동작은 멈추게 됩니다.
2. button submit 동작만 막기 (HTML)
undefined<button type="button">로그인</button>
button의 기본 type은 “submit”입니다. 폼 태그 안에 존재하는 버튼은 클릭 시 폼 데이터를 전송하는 시작점 역할을 가집니다. (Enter 등...)
하지만 해당 방법은 “Enter”와 같은 기타 submit 동작은 방지하지 못합니다.
참고자료
https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
Event.preventDefault() - Web APIs | MDN
The preventDefault() method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.
developer.mozilla.org