js
JS - form 다루기
폼 객체는 <form>태그에 접근할 수 있는 몇 가지 방법을 제시합니다. 형식은 다음과 같습니다.
속성을 이용한 예제입니다.
메서드를 이용해 폼을 취소하거나 전송해 보겠습니다.
document.폼이름.속성(or 메서드)
document.폼이름
속 성 | 설 명 |
---|---|
forms | 문서에 존재하는 모든 <form>을 배열에 담음 |
name | 폼의 name 의 속성 값 |
method | 폼의 method 의 속성 값 |
action | 폼의 action 의 속성 값 |
target | 폼 내용을 새 창으로 전송할지, 아니면 현재 창에서 전송할지를 설정.
|
elements | <form>태그 안의 폼 요소들을 배열로 반환 |
length | <form>태그 안의 폼 요소들의 개수를 반환 |
속성을 이용한 예제입니다.
<form name="frm" method="post" action="proc.php" target="_blank">
이름 <input type="text" name="youname" value="하보니">
나이 <input type="text" name="age" value="20">
직업 <input type="text" name="job" value="it">
비밀번호 <input type="password" name="pw" value="">
<input type="submit" name="frm_submit" value="전송">
</form>
<script>
document.write( "폼이름: " + document.frm.name + "<br/>");
// 폼이름: frm
document.write( "method: " + document.frm.method + "<br/>");
// method: post
document.write( "action: " + document.frm.action + "<br/>");
// action: http://localhost:8080/proc.php
document.write( "target: " + document.frm.target + "<br/>");
// target: _blank
document.write( "폼요소 개수: " + document.frm.length + "<br/>" );
// 폼요소 개수: 5
var frm_len = document.frm.length;
for(var i = 0; i < frm_len; i++){
var element = document.frm.elements[i];
document.write( "element[" + i + "]: " + element.name + "<br/>" );
}
/*
결과:
element[0]: youname
element[1]: age
element[2]: job
element[3]: pw
element[4]: frm_submit
*/
</script>
메서드를 이용해 폼을 취소하거나 전송해 보겠습니다.
<form name="frm" method="post" action="proc.php">
이름 <input type="text" name="youname" value="">
나이 <input type="text" name="age" value="">
<input type="submit" value="전송" onclick="frm_send()">
<input type="reset" value="취소" onclick="frm_cancel()">
</form>
<script>
// 폼을 전송합니다.
function frm_send() {
document.frm.submit();
alert("폼을 전송했습니다.");
}
// 폼을 초기화합니다.
function frm_cancel() {
document.frm.reset();
alert("폼을 취소하였습니다.");
}
</script>
다음은 문서에 있는 모든 폼을 찾습니다.
<form name="habony">
<input type="text" name="first" value="하보니">
</form>
<form name="php">
<input type="text" name="last" value="피에이치피">
</form>
<script>
var frm = document.forms;
for(var i = 0; i < frm.length; i++) {
document.write(
"frm[" + i + "] = " + frm[i].name + "<br/>"
);
document.write(
"input[" + i + "] = " + frm[i].elements[0].value + "<br/>"
);
}
/*
결과:
frm[0] = habony
input[0] = 하보니
frm[1] = php
input[1] = 피에이치피
*/
</script>
0 댓글