본문 바로가기

클라이언트/JavaScript
[자바스크립트(JavaScript)] Collection

// 내장 배열(컬렉션)

    - 문서 코드를 기반으로 자동 생성되는 배열을 제공한다.

    1. window.document.images: 문서 내의 모든 <img> 태그
    2. window.document.links: 문서 내의 모든 <a href=""> 태그
    3. window.document.anchors: 문서 내의 모든 <a name=""> 태그
    4. window.document.forms: 문서 내의 모든 <form> 태그
    5. window.document.forms[index].elements: 특정 <form> 태그 내의 모든 입력 태그
    6. window.document.forms[index].select.options: <option> 태그
    7. window.document.all: 문서상의 모든 태그: 비표준(MS)


// links


<!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>Document</title>
</head>
<body>
    <h1>링크</h1>

    <a href="http://naver.com" name="link1">네이버</a>

    <hr>

    <button type="button" name="btn1">확인</button>

    <script>

        document.all.btn1.onclick = m1;

        function m1() {

            //BOM
            document.links['link1'].href = 'http://google.com'
            document.links['link1'].target = '_blank';
            document.links['link1'].title = '구글로 이동합니다.';

            //DOM
            // document['link1'.innerTest] = '구글'; //비표준(MS)
            document.links['link1'].textContent = '구글' //표준
        }

    </script>

</body>
</html>

// images


<!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>Document</title>
</head>
<body>
    
    <h1>이미지</h1>

    <input type="button" value="확인" name="btn1">
    <hr>

    <img src="images/cat01.jpg" name="cat1">

    <hr>

    <img src="images/cat01.jpg" name="cat2">

    <script>

        document.all.btn1.onclick = m1;

        function m1() {
            var cat1 = document.images['cat1']

            // cat1.width = 500;

            cat1.src = 'images/cat02.jpg';
        }

        var cat2 = document.images['cat2'];

        //롤오버 이미지
        cat2.onmouseover = m2;
        cat2.onmouseout = m3;

        function m2() {
            cat2.src = 'images/cat02.jpg'
        }

        function m3() {
            cat2.src = 'images/cat01.jpg'
        }

    </script>

</body>
</html>

// forms


<!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>Document</title>
</head>
<body>
    
    <form name="form1" action="ex27_ok.jsp">
        <h1>회원가입</h1>

        <table border="1">
            <tr>
                <th>이름</th>
                <td><input type="text" name="txtname"></td>
            </tr>
            <tr>
                <th>나이</th>
                <td><input type="number" name="txtage" min="10" max="100"></td>
            </tr>
            <tr>
                <th>아이디</th>
                <td><input type="text" name="txtid"></td>
            </tr>
            <tr>
                <th>암호</th>
                <td><input type="text" name="txtpw"></td>
            </tr>
            <tr>
                <th>암호확인</th>
                <td><input type="password" name="txtpwc"></td>
            </tr>
        </table>
        <hr>
        <input type="button" value="가입하기" name="btn">

    </form>

    <script>

        document.form1.btn.onclick = m1;

        function m1() {

            var txtname = document.form1.txtname;
            var txtage = document.form1.txtage;
            var txtid = document.form1.txtid;
            var txtpw = document.form1.txtpw;
            var txtpwc = document.form1.txtpwc;

            //유효성 검사 > 잘못된 값을 찾기

            /*
                이름
                - 필수값
                - 2~5자 이내
                - 한글만
            */

            if(txtname.value == '') {
                alert('이름을 입력하세요.');
                txtname.focus();
                return; //진행 종료
            }

            if(txtname.value.length < 2 || txtname.value.length > 5) {
                alert('이름을 2-5자 이내로 입력하세요.');
                // txtname.focus();
                // txtname.value = ''; //텍스트박스 초기화
                txtname.select(); //텍스트박스 드래그한 상태
                return; //진행 종료
            }

            for (var i = 0; i < txtname.value.length; i++) {

                var c = txtname.value.charAt(i);

                if(c < '가' || c > '힣') {
                    alert('이름을 한글로 입력하세요.');
                    txtname.select();
                    return;
                }
            }

            /*
                나이
                - 필수값
                - 10-100살
                - 숫자만
            */

            if(txtage.value == '') {
                alert('나이를 입력하세요.');
                txtage.focus();
                return;
            }

            /*
                아이디
                - 필수값
                - 4-12자 이내
                - 영어+숫자+_
                - 숫자로 시작 불가
            */

            //JavaScript> 정규표현식 사용
            // var regex = /정규표현식/;
            var regex = /^[A-Za-z_][A-Za-z0-9_]{3,11}$/;

            if(!regex.test(txtid.value)) {
                alert('아이디를 올바르게 입력하세요.');
                txtid.select();
                return;
            }

            //암호 > 일치
            if (txtpw.value != txtpwc.value) {
                alert('암호가 일치하지 않습니다.');
                txtpw.focus();
                return;
            }

            //올바른 입력
            document.form1.submit();

        } //m1

    </script>

</body>
</html>

// forms.check


<!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>Document</title>
</head>
<body>
    
    <h1>체크 박스</h1>

    <form name="form1">
        <input type="checkbox" name="cb1">
        <input type="button" value="확인" name="btn1">
    </form>

    <hr>

    <h2>이용 약관</h2>

    <div style="width: 500px; height: 150px; overflow: auto; border: 1px solid black; padding: 10px;">lorem500</div>

    <hr>

    <label>
        <input type="checkbox" name="cbagree">
        약관에 동의합니다.
    </label>
    <hr>
    <input type="button" value="다음 단계로" disabled name="btnnext" onclick="location.href='ex27_form.html'">

    <hr>

    <h1>받은 편지함</h1>

    <table border="1" width="500px">
        <tr>
            <th><input type="checkbox" name="cball"></th>
            <th>번호</th>
            <th>제목</th>
            <th>보낸이</th>
            <th>날짜</th>
        </tr>
        <tr>
            <td><input type="checkbox" name="cbitem"></td>
            <td>10</td>
            <td>안녕하세요. 광고메일입니다.</td>
            <td>홍길동</td>
            <td>2023-04-24</td>
        </tr>
        <tr>
            <td><input type="checkbox" name="cbitem"></td>
            <td>10</td>
            <td>안녕하세요. 광고메일입니다.</td>
            <td>홍길동</td>
            <td>2023-04-24</td>
        </tr>
        <tr>
            <td><input type="checkbox" name="cbitem"></td>
            <td>10</td>
            <td>안녕하세요. 광고메일입니다.</td>
            <td>홍길동</td>
            <td>2023-04-24</td>
        </tr>
        <tr>
            <td><input type="checkbox" name="cbitem"></td>
            <td>10</td>
            <td>안녕하세요. 광고메일입니다.</td>
            <td>홍길동</td>
            <td>2023-04-24</td>
        </tr>
    </table>

    <script>

        var cb1 = document.form1.cb1;

        document.form1.btn1.onclick = m1;

        function m1() {
            // cb1.checked=true;
            cb1.checked = !cb1.checked;
        }

        // cb1.onclick = m2;
        cb1.onchange = m2; //입력 컨트롤의 값이 변할 때 발생하는 이벤트

        function m2() {
            console.log(cb1.checked);            
        }

        var cbagree = document.all.cbagree;
        var btnnext = document.all.btnnext;

        cbagree.onchange = m3;

        function m3() {
            if (cbagree.checked) {
                btnnext.disabled = false;
            } else {
                btnnext.disabled = true;
            }
        }

        var cball = document.all.cball;
        var cbitem = document.all.cbitem; //배열

        cball.onchange = m4;

        function m4() {

            for (var i = 0; i < cbitem.length; i++) {
                cbitem[i].checked = cball.checked;
            }

        }

    </script>

</body>
</html>

// forms.radio

* HTML 태그의 속성만 조작 가능하다. > HTML RGB 16진수만 지원


<!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>Document</title>
    <style>
        label { display: block;}
    </style>
</head>
<body>
    
    <h1>라디오 버튼</h1>
    <label><input type="radio" name="rb" value="white" vhrvkrf>흰색</label>
    <label><input type="radio" name="rb" value="red">빨간색</label>
    <label><input type="radio" name="rb" value="yellow">노란색</label>
    <label><input type="radio" name="rb" value="blue">파란색</label>
    <label><input type="radio" name="rb" value="black">검은색</label>

    <script>

        var rb = document.all.rb; //5개가 다 들어있음

        // console.log(rb[0]);
        
        for (var i = 0; i < rb.length; i++) {
            rb[i].onchange= m1;
        }

        function m1() {
            //5개의 라디오 버튼 중 누가 나를 불렀는지?
            // alert(event.target.value);            
            document.body.bgColor = event.target.value;

            if (event.target.value == 'black' || event.target.value == 'red' || event.target.value == 'blue') {
                document.body.text = 'white';
            } else {
                document.body.text = 'black';
            }
        }

    </script>

</body>
</html>

// forms.range


* oninput: 입력 컨트롤의 값이 변하는 것을 실시간으로 보여주는 이벤트


<!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>Document</title>
    <style>

        label {
            display: block;
            padding: 10px;
        }

        label input[type=range] {
            width: 300px;
        }

    </style>
</head>
<body>    

    <h1>배경색</h1>

    <label>R: <input type="range" name="red" min="0" max="255" value="255"></label>
    <label>G: <input type="range" name="green" min="0" max="255" value="255"></label>
    <label>B: <input type="range" name="blue" min="0" max="255" value="255"></label>

    <script>

        var red = document.all.red;
        var green = document.all.green;
        var blue = document.all.blue;

        // red.onchange = m1;
        // green.onchange = m1;
        // blue.onchange = m1;

        red.oninput = m1;
        green.oninput = m1;
        blue.oninput = m1;

        function m1() {
            // console.log(red.value, green.value, blue.value);

            var r = parseInt(red.value).toString(16); //16진수 변환
            var g = parseInt(green.value).toString(16); //16진수 변환
            var b = parseInt(blue.value).toString(16); //16진수 변환

            document.body.bgColor = '#' + r + g + b;

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

// forms.select.options

        ~ var 변수명 = new Option(content, value); > option 연결
        ~ document.all.select의 name 이름.selectedIndex; > 선택된 항목의 인덱스 반환
        ~ document.all.select의 name 이름.options.add(변수명); > 동적으로 추가
        ~ document.all.select의 name 이름.options.remove(index); > 특정 index의 요소 삭제(shift 발생)
        ~ document.all.select의 name 이름.options.remove(selectedIndex); > 선택된 요소 삭제


<!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>Document</title>
    <style>
        
        input {
            display: block;
            margin-bottom: 15px;
        }

    </style>
</head>
<body>
    
    <h1>셀렉트 박스</h1>

    <select name="sel1" multiple>
        <option value="a1">강아지</option>
        <option value="a2">고앙이</option>
        <option value="a3">돼지</option>
        <option value="a4">닭</option>
        <option value="a5">사자</option>
        <option value="a6">호랑이</option>
        <option value="a7">낙타</option>
    </select>

    <hr>

    <input type="button" value="선택한 항목 확인하기" name="btn1">
    <input type="button" value="선택한 항목 확인하기" name="btn2">
    <input type="button" value="항목 추가하기" name="btn3">
    <input type="button" value="항목 삭제하기" name="btn4">
    <input type="button" value="다중 선택 항목 확인하기" name="btn5">

    <hr>

    태어난 연도: <select name="selyear"></select>

    <script>

        var sel1 = document.all.sel1;

        document.all.btn1.onclick = m1;
        document.all.btn2.onclick = m2;
        document.all.btn3.onclick = m3;
        document.all.btn4.onclick = m4;
        document.all.btn5.onclick = m5;

        function m1() {
            //사용자가 어떤 <option>을 선택했는지?
            // alert(sel1.value); //읽기
           sel1.value = 'a3'; //쓰기            
        }

        function m2() {
            //프로퍼티
            sel1.selectedIndex = 2;
        }

        function m3() {
            //동적으로 <option> 생성하기
            // - <option value="a8"> 도마뱀</option>

            for (var i = 0; i < sel1.options.length; i++) {
                if (sel1.options[i].text == '도마뱀') {
                    return;
                }
            }

            var op = new Option(); // <option></option>
            op.value = 'a8';
            op.text = '도마뱀';

            //<select> + <option>
            sel1.options.add(op);
        }

        function m4() {
            //<option> 삭제
            // sel1.options.remove(3);

            //선택한 동물을 삭제하기
            sel1.options.remove(sel1.selectedIndex)
        }

        function m5() {
            
            //단일 선택
            //alert(sel1.value);

            //다중선택 (읽기)
            // for (var i = 0; i < sel1.options.length; i++) {
            //     // alert(sel1.options[i].selected);
            //     if(sel1.options[i].selected) {
            //         console.log(sel1.options[i].text, sel1.options[i].value);                    
            //     }
            // }

            //다중선택(쓰기)
            sel1.options[0].selected = true;
            sel1.options[1].selected = true;
            sel1.options[5].selected = true;
        }


        var selyear = document.all.selyear;

        for(var i=1960; i <=2010; i++) {
            var op = new Option(i +'년', i);
            selyear.options.add(op);
        }

        selyear.value = '1990';


    </script>

</body>
</html>