HTML

[HTML] javascript (2) - 응용

소댓 2023. 4. 16. 23:06

- 계산기

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>javascript13.html</title>
    <style>
        table, td {
            border: 1px solid gray;
            border-collapse: collapse;
            text-align: center;
        }
        table{
            width: 500px;
            height: 250px;
            margin: 0px auto;
        }
        input{
            width: 85px; 
        }
        /* 결과를 출력할 input의 너비를 350px
        폰트 크기를 25px
        글자는 bold */
        #result{
            width: 350px;
            font-size: 25px;
            font-weight: bold;
            text-align: right;
        }
    </style>
    <script>
        // function 함수명(매개변수)
        function inputData(v){
            console.log(v);
 
            // 1. result input 엘리먼트 객체 가져오기
            var resultEle = document.getElementById("result");
            // 2. 어떤 속성이 있는지 확인
            // console.log(resultEle);
            // console.dir(resultEle);
            // console.log(resultEle.value);
            // 3. 우리가 전달하는 값을 대입.. 브라우저가 자동으로 반영
            resultEle.value += v;
        }
        function cal() {
            // 1. id가 result인 엘리먼트의 값을 가져오기
            var resultEle = document.getElementById("result");
            var data = resultEle.value;
            console.log("data : "+data);
            // 한 문장으로도 가능!
            var data2 = document.getElementById("result").value;
            console.log("data2 : "+data2);
 
            // 2. 글자를 식으로 변환해주는 함수를...
            var result = eval(data2);
 
            // 3. id가 result인 엘리먼트의 값으로 지정
            data2 = result;
            // document.getElementById("result").value = result;
            resultEle.value = result;
        }
        function c(){
            document.getElementById("result").value = "";
        }
 
    </script>
</head>
<body>
    <!-- table>(tr>(td>input:button)*4)*4 -->
    <table>
        <tr>
            <td colspan="4">
                <input type="text" name="" id="result">
            </td>
        </tr>
        <tr>
            <td colspan="2"><input type="button" value="Clear" onclick="c();"></td>
            <td><input type="button" value="(" onclick="inputData('(')"></td>
            <td><input type="button" value=")" onclick="inputData(')')"></td>
        </tr>
        <tr>
            <td><input type="button" value="7" onclick="inputData(7);"></td>
            <td><input type="button" value="8" onclick="inputData(8);"></td>
            <td><input type="button" value="9" onclick="inputData(9);"></td>
            <td><input type="button" value="+" onclick="inputData('+');"></td>
        </tr>
        <tr>
            <td><input type="button" value="4" onclick="inputData(4);"></td>
            <td><input type="button" value="5" onclick="inputData(5);"></td>
            <td><input type="button" value="6" onclick="inputData(6);"></td>
            <td><input type="button" value="-" onclick="inputData('-');"></td>
        </tr>
        <tr>
            <td><input type="button" value="1" onclick="inputData(1);"></td>
            <td><input type="button" value="2" onclick="inputData(2);"></td>
            <td><input type="button" value="3" onclick="inputData(3);"></td>
            <td><input type="button" value="*" onclick="inputData('*');"></td>
        </tr>
        <tr>
            <td><input type="button" value="0" onclick="inputData(0);"></td>
            <td><input type="button" value="00" onclick="inputData('00');"></td>
            <td><input type="button" value="=" onclick="cal();"></td>
            <td><input type="button" value="/" onclick="inputData('/');"></td>
        </tr>
 
    </table>
 
</body>
</html>
cs

 

 


- 배송지 입력

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>javascript14.html</title>
    <script>
        // 함수명 : moveAddrs()
        function moveAddrs(){
            // id="addrs"인 엘리먼트 객체 가져오기
            var addrs = document.getElementById("addrs").value;
            // value 얻어오기
            console.log(addrs);
 
            // id="dest"인 엘리먼트 객체 가져오기
            // value에 대입
            document.getElementById("dest").value=addrs;
        }
    </script>
</head>
<body>
    <div>
        성명: <input type="text" name="" id="" value="홍길동">
        주소: <input type="text" name="" id="addrs" value="서울시 종로구 111">
    </div>
 
    <div><input type="button" value="배송지동일" onclick="moveAddrs();"></div>
    <div><input type="text" name="" id="dest"></div>
</body>
</html>
cs

 



- 자스에서 배열 사용 > Array

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>javascript15.html</title>
    <script>
        // 자바 스크립트에서 배열 사용 가능
 
        // int[] a = new int[3];
        var a = new Array(3);
 
        console.log(a);
        console.dir(a);
 
        a[0= 1;
        a[1= 2;
        a[2= 3;
 
        // 반복문을 사용해서 콘솔에 출력
        for(var i=0; i<a.length ; i++) {
           console.log(a[i]);
        }
 
    </script>
</head>
<body>
</body>
</html>
cs

 

 


- 날짜, 시간 출력 + 문자열

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>javascript16.html</title>
    <script>
        function getTime(){
            // console.log("test");
 
            // 자바에서 날짜 Date d = new Date();
            var now = new Date();
            console.log(now);
            console.dir(now);
 
            // 연도 구하기
            var year = now.getYear(); // 1900년 기준
            console.log(year);
 
            // 요즘에는
            var year2 = now.getFullYear();
            console.log(year2);
 
            var time = now.getFullYear() + "년 " + 
                (now.getMonth()+1+ "월 " + 
                now.getDate() + "일 " + 
                now.getHours() + "시 " +
                now.getMinutes() + "분 " +
                now.getSeconds() + "초";
            console.log(time);
 
            // text 창에서 보이게
            var timeEle = document.getElementById("time");
            timeEle.value = time;
 
            console.log("---------------")
 
            // 문자열 객체
            // String str = new String("ABCDEFG");
 
            var str = "ABCDEFG";
            
            console.log(str);
            console.dir(str);
 
            // 2번째부터 3글자
            console.log(str.substr(2,3));
 
            // 특정 문자의 위치
            // indexOf('A')
            console.log(str.indexOf('A'));
 
            // 중첩가능
            var email = "dagda@hanafos.com";
 
            // @ 문자 위치 ?
            var position = email.indexOf('@');
            console.log(position);
            // 이메일만 추출 가능
            console.log(email.substr(0,email.indexOf('@')));
 
            var friendList = "aaa,bbb,ccc,ddd,eee,fff";
            // split("기호")를 통해서 문자열을 짤라 배열 형태로 리턴
            var fList = friendList.split(",");
            console.log(fList);
 
            // 배열 요소를 반복문을 사용해서 콘솔에 출력
            for(var i=0; i<fList.length; i++) {
                console.log(fList[i]);
            }
 
        }
    </script>
</head>
<body>
    <input type="text" name="" id="time">
    <input type="button" value="지금시간출력하기" onclick="getTime();">
 
    <!--  버튼을 클릭하면 지금 현재 날짜 시간을 input:text에 출력 -->
</body>
</html>
cs

 

 



- MATH

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>javascript17.html</title>
    <script>
        console.log(Math.PI);
        console.log(Math.random());
        console.log(Math.sqrt(4));
        console.log(Math.abs(-9));
    </script>
</head>
<body>
    
</body>
</html>
cs

 

 

 

- 랜덤하게 영화 포스터..

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>javascript18.html</title>
    <style>
        img{
            width: 350px;
        }
    </style>
</head>
<body>
    <img id="poster" alt="">
    <script>
        function change_image(){
        // 1. id poster 엘리먼트 객체 가져오기
        var p = document.getElementById("poster");
 
        // 2. console.dir로 출력하기
        console.dir(p);
 
        // 3. 속성 중 이미지와 관련있는 속성 찾아보기
        // p.src="../images/movie_image3.jpg";
 
        // 4. 랜덤하게 정수를 생성
        var rnd = Math.random()*10;
        console.log(rnd);
 
        // 그 값을 넘지 않는 정수 9.234232 <== 9
       var no = Math.floor(rnd);
 
        // no : 0 ~ 9 값
        // 1부터 10까지
        console.log(no + 1);
        no++;
 
        p.src="../images/movie_image"+no+".jpg";
        }
    </script>
 
    <input type="button" value="변해라 얍" id="change" onclick="change_image();">
</body>
</html>
cs

 

 

 

-  네이버, 구글, 카카오 연결
console.log(document.getElemetById("login-password-input").value);

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>javascript19.html</title>
    <script>
        function goGoogle(){
            console.log("test");
            // 내장객체
            console.dir(location);
            location.href="http://www.google.com";
        }
        function goDaum(){
            location.href="http://www.daum.net";
        }
    </script>
</head>
<body>
    <a href="http://www.naver.com">네이버</a>
    <input type="button" value="구글" onclick="goGoogle();">
    <input type="button" value="카카오" onclick="goDaum();">
</body>
</html>
cs

 

 


- 랜덤 사이트 이동

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>javascript20.html</title>
    <script>
  
        function goRandom() {
            // 1. 배열 5칸짜리 생성
            var m = Array(5);
 
            // 2. 웹사이트의 url을 할당 
            // ex ) m[0] = "http://www.naver.com";
            // ex ) m[1] = "http://www.mcdonalds.co.kr";
            m[0= "http://www.naver.com";
            m[1= "http://www.mcdonalds.co.kr";
            m[2= "http://www.daum.net";
            m[3= "http://www.google.com";
            m[4= "http://www.nate.com";
 
            // 3. 버튼을 클릭하면 랜덤하게 5개의 사이트 중 1곳으로 이동
                var no =  Math.floor((Math.random())*5); // 0~4
                
                // 4. 이동
                location.href=m[no];
        }
 
    </script>
</head>
<body>
    <input type="button" value="랜덤사이트로이동" onclick="goRandom();">
</body>
</html>
cs

 

 

 

- 영화 체크

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>javascript21.html</title>
    <script>
        function viewResult(){
            // console.log("test");
            var m1 = document.getElementById("m1");
            var m2 = document.getElementById("m2");
            var m3 = document.getElementById("m3");
            var m4 = document.getElementById("m4");
            var m5 = document.getElementById("m5");
 
            console.dir(m1);
            console.log(m1.checked);
 
            if(m1.checked){
                console.log("스즈메의 문단속");
            }else if(m2.checked){
                console.log("던전앤드래곤");
            }else if(m3.checked){
                console.log("더퍼스트슬램덩크");
            }else if(m4.checked){
                console.log("웅남이");
            }else if(m5.checked){
                console.log("리바운드");
            }
            console.log("------------");
            console.dir(document);
            console.log(document.frm.movie[0].checked); // 체크되었다면 true
        }
    </script>
</head>
<body>
    <h1>추천영화</h1>
    <form action="" name="frm">
        <!-- input:radio[name='movie']#m$*5 -->
        <input type="radio" name="movie" id="m1">스즈메의문단속
        <input type="radio" name="movie" id="m2">던전앤드래곤
        <input type="radio" name="movie" id="m3">더퍼스트슬램덩크
        <input type="radio" name="movie" id="m4">웅남이
        <input type="radio" name="movie" id="m5">리바운드
        <input type="button" value="추천" onclick="viewResult();">
    </form>
</body>
</html>
cs

 

 

 

- 햄버거 선택 > 이동

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>javascript22.html</title>
    <script>
        function printWhere() {
            // console.log("test");
            console.dir(document.frm.where);
            console.log(document.frm.where.selectedIndex);
            // selectedIndex : 몇 번째 인덱스를 선택했는지
 
            var addrs = new Array(5);
            addrs[1= "http://www.burgerking.co.kr";
            addrs[2= "http://momstouch.co.kr";
            addrs[3= "http://www.subway.co.kr";
            addrs[4= "http://mcdonalds.co.kr";
 
 
            location.href=addrs[document.frm.where.selectedIndex];
        }
    </script>
</head>
<body>
    <h1>당신이 좋아하는 패스트푸드점은?</h1>
    <form action="" name="frm">
    <!-- onchange : 다른 거 선택 -->
        <select name="where" id="sel" onchange="printWhere();"> 
            <option value="">-----------------</option>
            <option value="버거왕">버거왕</option>
            <option value="엄마손">엄마손</option>
            <option value="지하철">지하철</option>
            <option value="마크도날르도">마크도나르도</option>
    </select>
    </form>
</body>
</html>
cs

 


- 회원가입

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>javascript23.html</title>
    <script>
        function checkForm(){
            // console.log("TEST");
 
            // 입력한 값 콘솔에 출력
            var id = document.getElementById("id");
            console.log("id : " + id.value);
 
            var pw = document.getElementById("pw");
            console.log("pw : " + pw.value);
           
            var pw2 = document.getElementById("pw2");
            console.log("pw2 : " + pw2.value);
 
            var email = document.getElementById("email");
            console.log("email : " + email.value);
 
            id = id.value;
            pw = pw.value;
            pw2 = pw2.value;
            email = email.value;
 
            if(id=="") {
                alert("아이디를 입력하세요.");
            }else if(pw=="") {
                alert("비밀번호를 입력하세요.");
            }else if(pw2==""){
                alert("비밀번호확인을 입력하세요.");
            }else if(email==""){
                alert("이메일을 입력하세요.");
            }else if(pw.length <= 7){
                alert("패스워드의 길이는 8자 이상이어야 합니다.");
            }else if(pw != pw2){
                alert("비밀번호가 일치하지 않습니다.");
            }else if(email.indexOf('@'== -1) {
                alert("메일을 형식에 맞게 적어주세요.");
            }
        }
    </script>
</head>
<body>
    <form action="next.html">
        <table>
            <tr>
                <td>아이디</td>
                <td><input type="text" name="useridid" id="id"></td>
            </tr>
            <tr>
                <td>비밀번호</td>
                <td><input type="text" name="userpw" id="pw"></td>
            </tr>
            <tr>
                <td>비밀번호확인</td>
                <td><input type="text" name="userrepw" id="pw2"></td>
            </tr>
            <tr>
                <td>email</td>
                <td><input type="text" name="email" id="email"></td>
            </tr>
            <tr>
                <td colspan="2">
                <input type="button" value="전송1" onclick="checkForm();">
                <input type="submit" value="전송2">
                </td>
            </tr>
        </table>
        
 
 
    </form>
</body>
</html>
cs

 


- 회원가입(form) & next.html로 보내기

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>javascript24.html</title>
    <script>
        function checkForm(x){
            // console.log(x);
            // console.dir(x);
 
            console.dir(x.form);
            // id.value
            console.log(x.form[0]);
            console.log(x.form[0].value); // 사용자가 입력한 아이디
 
            // 패스워드 입력값을 콘솔에 출력
            console.log(x.form[1].value);
 
            var id = x.form[0].value;
            var pw = x.form[1].value;
            var pw2 = x.form[2].value;
            var email = x.form[3].value;
           
            // 콘솔에 출력
            // var id = document.getElementById("id");
            console.log("id : " + id);
 
            // var pw = document.getElementById("pw");
            console.log("pw : " + pw);
           
            // var pw2 = document.getElementById("pw2");
            console.log("pw2 : " + pw2);
 
            // var email = document.getElementById("email");
            console.log("email : " + email);
 
            // id = id.value;
            // pw = pw.value;
            // pw2 = pw2.value;
            // email = email.value;
 
            if(id=="") {
                alert("아이디를 입력하세요.");
                x.form[0].focus();
                // 실행중인 함수를 중단 > 입력 안하면 다음 화면으로 넘어가지 않도록
                return
 
           }else if(pw=="") {
                alert("비밀번호를 입력하세요.");
                x.form[1].focus();
                return
            }else if(pw2==""){
                alert("비밀번호확인을 입력하세요.");
                x.form[2].focus();
                return
            }else if(email==""){
                alert("이메일을 입력하세요.");
                x.form[3].focus();
                return
            }else if(pw.length <= 7){
                alert("패스워드의 길이는 8자 이상이어야 합니다.");
                return
            }else if(pw != pw2){
                alert("비밀번호가 일치하지 않습니다.");
                // 기존에 입력했던 값은 지우고 다시 입력
                x.form[1].value='';
                x.form[2].value='';
                x.form[1].focus();
                return
            }else if(email.indexOf('@'== -1) {
                alert("메일을 형식에 맞게 적어주세요.");
                return
            }
 
            // 조건 검사를 성공했다면
            // next.html에 이 값들을 전송
            // action
            x.form.action="next.html";
            // method : get방식
            x.form.method="get";
            // 제출
            x.form.submit();
        }
    </script>
</head>
<body>
    <!-- get 방식으로 보내면, querry string으로 전달 -->
    <!-- oost 방식으로  -->
    <form action="next.html" method="get"> 
        <table>
            <tr>
                <td>아이디</td>
                <td><input type="text" name="useridid" id="id"></td>
            </tr>
            <tr>
                <td>비밀번호</td>
                <td><input type="text" name="userpw" id="pw"></td>
            </tr>
            <tr>
                <td>비밀번호확인</td>
                <td><input type="text" name="userrepw" id="pw2"></td>
            </tr>
            <tr>
                <td>email</td>
                <td><input type="text" name="email" id="email"></td>
            </tr>
            <tr>
                <td colspan="2">
                <input type="button" value="전송1" onclick="checkForm(this);">
                <input type="submit" value="전송2">
                </td>
            </tr>
        </table>
        
 
 
    </form>
</body>
</html>
cs

 

> next

 

 

1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>next.html</title>
</head>
<body>
    <h1>next.html 파일 입니다.</h1>
    <h2>아직 웹 서버가 없어서 값을 전달 받을 수 없어요.. 나중에 해요</h2>
</body>
</html>
cs

 


- 사진 바꾸기(뽀로로)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>javascript25.html</title>
    <script>
        function changeImage(){
            // console.log("test");
            // 객체를 가져와서 image의 src를 바뀐 이미지로 바꿔주면 이미지가 바뀜..
            var photo = document.getElementById("photo");
            console.dir(photo);
            console.log(photo.src);
 
            photo.src="../images/after.PNG";
        }
        function changeImage2() {
            var photo = document.getElementById("photo");
            photo.src="../images/before.PNG";
        }
    </script>
</head>
<body>
    <img src="../images/before.PNG" alt="원래 뽀로로 이미지" id="photo" 
    onmouseover="changeImage();" onmouseout="changeImage2();">
</body>
</html>
cs