[JavaScript] 폼 조작하기
1. forms 속성 사용하기
모든 form 태그의 노드 정보를 HTML collection 객체에 담아 반환한다. -> form 요소 노드 쉽게 선택 가능.
하지만, form 태그 위치가 바뀌면 잘 못 참조할 수 있는 오류 발생 가능.
2. name 속성 사용하기
forms 속성보다 훨씬 직관적으로 form 요소 노드를 선택할 수 있다.
<body>
<form name="frm1">
<input type="text">
</form>
<form name="frm2">
<input type="text">
</form>
<form name="frm3">
<input type="text">
</form>
</body>
위와 같은 코드가 있을 때, name 속성값으로 form 요소에 접근할 수 있다.
document.frm1; // form 태그의 name 속성값이 frm1인 노드
document.frm2; // form 태그의 name 속성값이 frm2인 노드
form 요소에는 input태그, select태그, button 태그 등이 있다.
이런것들을 elements 속성이나 name 속성을 사용해서 접근할 수 있다.
elements 속성은 form 요소 노드의 하위 노드 중 폼 요소 노드만 반환하는 속성이다.
document.frm1.elements를 통해 HTMLFromControlsCollection 객체에 여러개의 노드를 담아 반환한다.
그래서 인덱스를 사용 or name 속성값을 사용하는 방법 중 하나 선택 가능.
document.frm1.elements[0]; // 0번 인덱스 노드
document.frm1.elements['uname']; // form 요소 노드의 하위 노드 중에서 name 속성값이 uname인 노드
입력값 다루기
1. 한줄입력 다루기
input 태그의 type 속성값을 text, password, number, url, search, email 등으로 지정했을 때 표시되는 폼 요소
사용자가 입력한 값을 가져오려면 value 속성을 사용한다.
ex) document.frm.id.value;
document.frm.pw.value;
할당기호(=)를 사용해서 해당 입력칸에 값을 할당할 수도 있다.
<script>
document.frm.id.value = 'jscoding';
document.frm.pw.value = 'aaaccc';
</script>
여러 줄 요소 다루기
: textarea 태그를 대표적으로 활용할 수 있다.
이것도 마찬가지로 value 속성을 통해 값을 할당하고 가져올 수 있다.
<form name="frm">
<textarea name="desc"></textarea>
</form>
<script>
document.frm.desc.value = 'setting!';
</script>
체크박스 다루기
체크박스에 체크표시가 되어있는지 checked 속성으로 확인할 수 있다.
아래 코드에서처럼 만약 체크되어있으면 value값을 가져오는 것을 설정할 수 있다.
<form>
<label><input type="checkbox" value="apple">사과</label>
<label><input type="checkbox" value="banana">바나나</label>
<label><input type="checkbox" value="orange">오렌지</label>
<label><input type="checkbox" value="melon">멜론</label>
</form>
const checkboxEls = document.querySelectorAll("[type='checkbox']");
for(let i = 0; i < checkboxEls.length; i++){
if(checkboxEls[i].checked === true){
console.log(checkboxEls[i].value);
}
}
초기 설정으로 모두 체크표시를 하고싶다면 아래와 같이 설정할 수 있다.
checkboxEls[i].checked = true;
라디오 버튼 다루기
: 라디오 버튼은 여러개의 항목 중 하나만 선택하게 할 때 사용하는 폼 요소.
이것도 체크박스와 마찬가지로 checked 속성으로 선택됐는지 확인하고 value 속성으로 값을 가져오면 됨
<form>
<label><input type="radio" name="fruits" value="apple">사과</label>
<label><input type="radio" name="fruits" value="banana">바나나</label>
<label><input type="radio" name="fruits" value="orange">오렌지</label>
<label><input type="radio" name="fruits" value="melon">멜론</label>
</form>
const radioEls = document.querySelectorAll("[type='radio']");
for(let i = 0; i < radioEls.length; i++){
if(radioEls[i].checked === true){
console.log(radioEls[i].value);
}
}
콤보박스 다루기
: select 태그로 만드는 콤보박스는 여러 항목에서 하나를 선택하는 형태의 폼 요소
selected 속성으로 선택항목을 확인할 수 있다.
<form>
<select>
<option value="apple">사과</option>
<option value="banana">바나나</option>
<option value="orange">오렌지</option>
<option value="melon">멜론</option>
</select>
</form>
const optionEls = document.querySelectorAll("option");
for(let i = 0; i < optionEls.length; i++){
if(optionEls[i].selected === true){
console.log(optionEls[i].value);
}
}
파일 업로드 요소 다루기
: input 태그의 type 속성값을 file로 지정하면 표시되는 요소.
: 파일 업로드 요소에서 핵심은 files 속성으로 반환되는 FileList 객체.
<body>
<form name = "fn">
<input type="file" name="upload">
</form>
</body>
여기서 이미지 하나를 업로드 하면,
업로드를 하고 console창에서 해당 코드 2줄을 입력하면 FileList 객체의 속성이 나온다.
사진에서 볼 수 있듯이 속성3개와 함께 type까지 확인할 수 있다. 아래 코드 참고.
const files = document.frm.upload.files;
files[0].name; // 파일 이름
files[0].size; // 파일 크기
files[0].type; // 파일 타입
files[0].lastModifiedDate; // 파일 마지막 수정일
폼 요소 관련 기타 메서드
그 외 관련 메서드는 아래에서 더 확인이 가능하다.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement
HTMLFormElement - Web APIs | MDN
The HTMLFormElement interface represents a <form> element in the DOM. It allows access to—and, in some cases, modification of—aspects of the form, as well as access to its component elements.
developer.mozilla.org
그리고 앞에서 공부한 form에 대해 다시 되돌아가야한다면 아래 포스팅 참고!!
https://daywnme.tistory.com/333
[HTML] 폼(form) 태그 다루기
폼 (form) 이란? : HTML에서 사용자와 상호작용해서 정보를 입력받고 서버로 전송하기 위한 양식. form 태그 : 폼 양식을 의미하는 태그 -> 폼을 구성하는 태그는 모두 form 태그 안에 작성. action 속성 :
daywnme.tistory.com