본문 바로가기

JS/JavaScript

[JavaScript] 폼객체

728x90

폼 객체(window 객체의 하위 객체)

    <form name="myform" id="regform">
        <input type="text" name="userid" id="id"> // apple 작성
        <input type="password" name="userpw" id="pw">
    </form>

    <form name="myform" id="etcform">
        <input type="text" name="comment" id="comment">
    </form>


폼의 접근
const frm = document.myform; // name을 통해 접근
const frm = document.getElementById('regform'); // id를 통해 접근
const frm = document.forms[0]; // regform
const frm1 = document.forms[1]; // etcform

아이디 value 접근
const id = document.myform.userid.value; // apple
const id = frm.userid.value; // apple
const id = frm.elements[0].value; // apple
const id = frm.elements['userid].value; // apple
const id = document.getElementById('id').value // apple
const id = document.forms[0][0].value; // apple

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>폼 객체</title>
</head>
<body>
    <h2>폼 객체</h2>
    <form action="#" name="frm1">
        <input type="search" name="search" placeholder="검색어를 입력하세요">
        <input type="submit" value="확인">
    </form>
    <form action="#" name="frm2">
        <input type="text" name="userid" id="id" placeholder="아이디를 입력하세요" value="apple"><br>
        <input type="password" name="userpw" placeholder="비밀번호를 입력하세요"><br>
        <input type="submit" value="확인">
    </form>
    <script>
        'use strict';

        const frm1 = document.frm1;
        const frm2 = document.frm2;

        console.log(frm1.search.placeholder); 
        // 검색어를 입력하세요 첫번째 폼의 name이 search인 요소의 placeholder
        
        console.log(frm2.userid.placeholder); 
        // 아이디를 입력하세요 두번째 폼의 name이 userid인 요소의 placeholder
        
        console.log(frm2.userid.value); 
        // apple 두번째 폼의 name이 userid인 요소의 value
        
        console.log(document.forms[1][0].value); 
        // apple 두번째 폼의 첫번째 요소의 value
        
        console.log(document.forms['frm2'].elements['userpw'].value); 
        // 값 없음. 두번째 폼의 name이 userpw인 요소의 value
        
        console.log(document.getElementById('id').value); 
        // apple id가 id인 요소의 value
        

    </script>
</body>
</html>

정규표현식
- 문자열에 특정 문자 조합과 대응시키기 위해 사용되는 패턴
https://developer.mozilla.org/ko/docs/Web/JavaScript/Guide/Regular_Expressions

test() 
- 정규표현식에 대입한 문자열이 부합하면 true, 아니면 false를 반환

    정규표현식객체.test('비교할 문자열');
    const expNameText = /[가-힣]+$/
    expNameText.text('유영은');     // true
    expNameText.text('유1영은1');   // false


hidden
눈에 보이지 않는 요소
    <input type="hidden">


다음 카카오 우편번호 API
'구글에서 다음 우편번호 API 검색'https://postcode.map.daum.net/guide

728x90