평범한 연구소

[JSP|Servlet] submit 관련 버튼 본문

Pront/Javascript

[JSP|Servlet] submit 관련 버튼

soyeonisgood 2022. 10. 2. 14:42

submit

  • submit 버튼은 form 태그 안에 있어야, 파라미터를 서버로 전송한다.
  • 마찬가지로 reset 버튼도 form 태그 안에 있어야 초기화가 된다.
  • submit 버튼의 종류
    • <button> 전송 </button>
    • <button type="submit> 전송 </button>
    • <input type="submit" value="전송">
    • <input type="image" src="이미지">
  • input 요소의 required 속성과 pattern 속성은 form 태그 안에 submit 버튼으로 요청할 때 유효하다.
  • 주의할 점
    • <input type="text"> 가 하나만 있는 경우
    • <input type="text"> 에서 엔터를 치면 서버로 바로 전송된다. 즉, submit() 기능이 있다.
    • 이럴 땐, 해당 태그를 하나 더 만들고 display="none" 속성을 주면 해결된다.
      • <input type="text" style="display:none">

 

submit 관련 예제

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ page trimDirectiveWhitespaces="true" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<form action="ex03_ok.jsp" method="post">
	<p> 이름 : <input type="text" name="name"> </p>
	<p> 나이 : <input type="text" name="age"> </p>
	<p>
		<button>전송</button> |
		<button type="submit">전송</button> |
		<input type="submit" value="전송"> |
		<input type="image" src="btn_submit.gif" style="vertical-align: bottom;"> |
		<button type="button">일반버튼-전송안됨</button>
		<button type="reset">초기화</button>
	</p>
</form>

<form action="ex03_ok.jsp" method="post">
	<p> 나이 : <input type="text" name="age"> </p>
	<input type="text" style="display:none">
	<p>
		<button type="button" onclick="sendOk();">일반버튼-전송안됨</button>
	</p>
</form>

<script type="text/javascript">
function sendOk() {
	const f = document.forms[1];
	if( ! /^\d{1,3}$/.test(f.age.value) ) {
		f.age.focus();
		return;
	}
	
	f.submit();
}

</script>


</body>
</html>

 

  • 일반 버튼은 submit 기능이 없으므로 js에서 document.Form이름.submit() 을 해주어야 서버로 전송된다.
  • submit 버튼이나 이미지 버튼은 submit 기능이 있으므로 이 버튼의 함수에 submit()을 호출하면 서버로 데이터가 두 번 전송된다. 유의할 것.
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ page trimDirectiveWhitespaces="true" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<h3>submit</h3>

<form name="myForm" action="ex04_ok.jsp" method="post">
	<p> 이름 : <input type="text" name="name"> </p>
	<p> 나이 : <input type="text" name="age"> </p>
	<p>
		<button type="button" onclick="sendOk()">전송</button>
		<button type="reset">초기화</button>
	</p>
</form>


<script type="text/javascript">
function sendOk() {
	const f = document.myForm;
	
	if( ! f.name.value ){
		f.name.focus();
		return;
	}
	
	if( ! /^\d{1,3}$/.test(f.age.value) ) {
		f.age.focus();
		return;
	}
	
	f.submit();
		// submit 버튼에서 submit() 함수를 호출하면 서버로 두 번 전송됨
		// submit 버튼이나 이미지 버튼에서는 절대로 submit() 함수 호출하지 않는다.
}

</script>


</body>
</html>