개발자 미니민의 개발스터디

[javascript] form 객체 / form 서버 전송

by mini_min
[javascript] form 객체 / form 서버 전송

✔️ form 객체

: document.forms 속성은 현재 문서의 <form> 요소 목록을 반환한다.

<form> 요소를 접근할 때는 폼의 이름이나 인덱스를 이용해 접근한다.

document.forms[인덱스];

document.forms["폼이름"]

 

👩‍💻 폼에 이름을 주면 이름으로 쉽게 접근할 수 있다.

document.폼이름

 

 

✔️ form 태그 내용 서버 전송하기

ation : form 요소의 내용을 서버로 전송할 때 전송한 데이터를 받을 서버 주소를 적는다.

👩‍💻 서버에 전송할 때, name 속성이 없으면 서버에서 받을 수 없다. id 속성으로는 서버 전송 불가 ❌

<form name="myForm" action="request.jsp" method="post" enctype="application/x-www-form-urlencoded">
	<p> 이름 : <input type="text" name="name"> </p>
	<p> 과목 : <input type="text" id="subject"> </p> 
	<!--  name 속성이 없으면 서버에서 받을 수 없다. -->
	<!--  id 속성으로는 서버로 전송이 안된다. -->
	<p> 점수 : <input type="text" name="score"> </p>
	<p>
		<button type="button" onclick="send();">서버로 전송</button>
	</p>
</form>

<script type="text/javascript">
//자바스크립트로 서버 전송 버튼 만들기

function send(){
	const f = document.myForm;
	f.submit(); //submit 버튼이 아닌 !!!button 등으로 서버로 전송할 때!!! 호출
	// submit 버튼에서 submit() 함수를 호출하면 서버로 두번 전송된다(DB 작업하면 두번 저장됨)
	//깨알 : 이미지 버튼도 submit()
}

💡 submit() 함수를 호출하면 서버로 전송하는데,
submit 버튼에서 submit() 함수를 호출하면 서버로 두번 전송된다(DB 작업하면 두번 저장됨)

 

 

✔️ form 객체 유효성 검사 (submit 버튼)

<form name="myForm" action="request.jsp" method="post">
	<p> 이름 : <input type="text" name="name"> </p>
	<p> 과목 : <input type="text" name="subject"> </p> 
	<p> 점수 : <input type="text" name="score"> </p>
	<p>
		<button type="submit">서버로 전송</button>
	</p>
</form>
function check(e){
	const f = document.myForm;
	
	if(! f.name.value) {
		alert("이름..!!");
		f.name.focus();
		e.preventDefault();
		return false; // 서버로 전송되지 않음
	}
	
	if(! f.subject.value) {
		alert("과목..!!");
		f.name.focus();
		e.preventDefault();
		return false; 
	}
	
	if(! /^\d+$/.test(f.score.value)){
		alert("점수..!!");
		f.score.focus();
		e.preventDefault();
		return false; 
	}
	
	// submit 버튼은 절대로 submit() 함수를 호출하면 안된다.
	return true; //서버로 전송

}

document.myForm.addEventListener("submit", (e) => check(e));

💡 submit 버튼에서 submit 함수 호출 ❌❌❌❌
submit 이벤트가 발생되면 check(e) 함수가 실행된다.

 

 

✔️ form 객체 유효성 검사 (button 버튼)

function send(){
	const f = document.myForm;
	
	if(! f.name.value) {
		alert("이름..!!");
		f.name.focus();
		return ; // 서버로 전송되지 않음
	}
	
	if(! f.subject.value) {
		alert("과목..!!");
		f.name.focus();
		return ; 
	}
	
	if(! /^\d+$/.test(f.score.value)){
		alert("점수..!!");
		f.score.focus();
		return ; 
	}
	
	f.submit(); //서브밋 버튼이 아닌 일반 버튼등을 이용하여 서버로 전송하는 경우 
	
	
}

💡 button 타입인 버튼에서는 submit() 함수 가능

 

+ 깨알로 서브밋 버튼일 때는 인라인에서 pattern 속성 사용 가능하다.

	<p> 점수 : <input type="text" name="score" 
				required="required" pattern="\d+"> </p>
				<!--  서브밋 버튼일 때만 먹힌다. 패턴  -->

 

 

 

 

블로그의 정보

개발자 미니민의 개발로그

mini_min

활동하기