HTML의 onsubmit 이벤트 속성은 폼(form)이 제출되는 순간에 지정된 자바스크립트 코드를 실행하는 기능입니다. 사용자가 입력한 데이터를 서버로 전송하기 전에 유효성 검사를 하거나, 확인 대화상자를 띄우는 등 다양한 용도로 활용할 수 있습니다.
기본 문법
onsubmit 이벤트 속성의 기본적인 작성 형식은 다음과 같습니다.
<tagname onsubmit="script"></tagname>
이제 실제 예제를 통해 onsubmit 이벤트 속성이 어떻게 동작하는지 살펴보겠습니다.
예제 코드
<!DOCTYPE html>
<html>
<head>
<style>
body {
color: #000;
height: 100vh;
background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) no-repeat;
text-align: center;
padding: 20px;
}
textarea {
border: 2px solid #fff;
background: transparent;
font-size: 1rem;
}
::placeholder {
color: #000;
font-size: 1rem;
}
.btn {
background: #db133a;
border: none;
height: 2rem;
border-radius: 2px;
width: 40%;
display: block;
color: #fff;
outline: none;
cursor: pointer;
margin: 1rem auto;
}
</style>
</head>
<body>
<h1>HTML onsubmit Event Attribute Demo</h1>
<form onsubmit="submitFn()">
<textarea placeholder="Enter your message here" rows='8' cols="50"></textarea>
<input type="submit" value="SUBMIT" class="btn">
</form>
<div class="show"></div>
<script>
function submitFn() {
confirm("Form was submitted");
}
</script>
</body>
</html>실행 결과

위 화면에서 텍스트 영역에 메시지를 입력한 뒤 SUBMIT 버튼을 클릭해 보세요.

버튼을 클릭하면 폼이 제출되면서 onsubmit 이벤트 속성에 연결된 submitFn() 함수가 호출되고, "Form was submitted(폼이 제출되었습니다)"라는 확인 대화상자가 나타나는 것을 확인할 수 있습니다.
정리
onsubmit 이벤트 속성은 <form> 요소에서만 사용할 수 있으며, 폼 제출 동작과 함께 실행되어야 하는 로직을 처리할 때 유용합니다. 특히 클라이언트 측 유효성 검사를 통해 잘못된 데이터가 서버로 전송되는 것을 사전에 차단할 수 있어 웹 개발에서 매우 자주 활용되는 속성입니다.