FE - JS, jQuery 미션

수현·2023년 9월 28일
0

Ucamp

목록 보기
11/19

📒 JavaScript

📕 JS 미션1

문제1. var 변수

  • 📋 코드 📋
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript">
     var name = "홍길동";
     var age = 20;
     var address="서울";
     var isMarried=false;
     var weight=73.5;
     var height=173.2;
     
     console.log("이름은:" + name);
     console.log("나이는:" + age);
     console.log("주소는:" + address);
     console.log("결혼여부:" + isMarried);
     console.log("체중:" + weight);
     console.log("키:" + height);
    </script>
    </head>
    <body>
    </body>
    </html>

문제2. parseInt

  • 📋 코드 📋
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript">
    	var n = prompt("1.정수값을 입력하시오.")
    	var n2 = prompt("2.정수값을 입력하시오.")
    	
    	console.log("첫번째 입력값은: "+n);
    	console.log("두번째 입력값은: "+n2);
    	console.log("두 값의 합계: " + (parseInt(n)+parseInt(n2)));
    </script>
    </head>
    <body>
    </body>
    </html>

문제3. 나머지 (%)

  • 📋 코드 📋
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript">
    	var n = prompt("정수값을 입력하시오.")
    	var mesg="";
    	
    	if(n%3==0){
    	   mesg+=" foo";	
    	}
    	if(n%5==0){
    		   mesg+=" bar";	
    	}
    	if(n%7==0){
    		   mesg+=" baz";	
      }
    	console.log("입력값:"+n+" " + mesg);
    </script>
    </head>
    <body>
    </body>
    </html>

문제4. isNaN, if문

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8" />
      <title>Insert title here</title>
      <script type="text/javascript">
        var value = prompt("1.정수값을 입력하시오.");
        if (isNaN(value)) {
          alert("입력한 값이 숫자가 아닙니다!");
        }else {
          var int_value = Number(value);
          if(int_value < 1 && int_value > 100 ){
              alert(" 값은 1 ~ 100 사이의 값만 가능합니다!");
          }else {
              grade(int_value);            
          }
        }
    
        function grade(n) {
          var grade = "";
          if ( n >= 90 ) {
            grade = "1 등급";
          } else if ( n >= 80 ) {
            grade = "2 등급";
          } else if ( n >= 70 ) {
            grade = "3 등급";
          } else {
            grade = "4등급";
          }
          console.log("입력값: " + n);
          console.log("등급: " + grade);
        }
      </script>
    </head>
    <body></body>
    </html>

문제5. max

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript">
    	var n = prompt("1.정수값을 입력하시오.")
    	var n2 = prompt("2.정수값을 입력하시오.")
    	var n3 = prompt("3.정수값을 입력하시오.")
    
    	console.log("첫번째 입력값은: "+n);
    	console.log("두번째 입력값은: "+n2);
    	console.log("세번째 입력값은: "+n3);
    
       n = parseInt(n);
       n2 = parseInt(n2);
       n3 = parseInt(n3);
    
       var temp = (n > n2)? n:n2;
       var max = (temp > n3)? temp:n3;
    
       console.log("가장 큰 값: " + max );
    </script>
    </head>
    <body>
    </body>
    </html>

문제6. 이중 for문

  • 📋 코드 📋
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript">
    for(var i=1;i<=6;i++) {
       for(var j=1;j<=6;j++) {
         if( (i+j) ==6 ) {
            console.log(i+"+"+j+"="+(i+j));
         }
       }
    }  
    </script>
    </head>
    <body>
    </body>
    </html>

문제7. 3중 for문

  • 📋 코드 📋
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript">
    for (var inx = 1; inx <= 6; inx++) {
       for (var jnx = 1; jnx <= 6; jnx++) {
          for (var knx = 1; knx <= 6; knx++) { 
             if( (inx * jnx * knx) % 3 == 0) {
    console.log(inx + "*" + jnx + "*" + knx + " = "
    + (inx * jnx * knx));
             } //if
           }//for
         }//for
    }//for
    </script>
    </head>
    <body>
    </body>
    </html>

📕 JS 미션2

문제1. 선언적 방법 함수 정의

  • 📋 코드 📋
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript">
     function fun(){
    	   console.log("hello");
     }
     fun();
    </script>
    </head>
    <body>
    </body>
    </html>

문제2. 익명 함수 정의

  • 📋 코드 📋
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script>
     var result = function() {
        return "안녕하세요";      
     }
     console.log(result());
    </script>
    </head>
    <body>
    </body>
    </html>

문제3. even 판별 함수

  • 📋 코드 📋
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8" />
      <title>Insert title here</title>
      <script type="text/javascript">
        // 방법 1
        function even(x1, x2, x3, x4, x5) {
          var s = 0;
          if (x1 % 2 === 0) {
            s += x1;
          }
          if (x2 % 2 == 0) {
            s += x2;
          }
          if (x3 % 2 == 0) {
            s += x3;
          }
          if (x4 % 2 == 0) {
            s += x4;
          }
          if (x5 % 2 == 0) {
            s += x5;
          }
          return s;
        }
        var mesg = even(1, 2, 3, 4, 5);
        console.log(mesg);
        
        // 방법 2
        function even2(x1, x2, x3, x4, x5) {
          argumentsArray = Array.from(arguments);
          let sumEvenValue = argumentsArray
            .filter((val) => val % 2 === 0)
            .reduce((n1, n2) => n1 + n2);
          return sumEvenValue;
        }
        var result = even2(1, 2, 3, 4, 5);
        console.log(result);
      </script>
    </head>
    <body></body>
    </html>

문제4. length

  • 📋 코드 📋
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript"> 
    // 방법 1
    function xyz(m){
    	   return m.length;
     }
     
     var len = xyz('hello');
     console.log("hello 문자열 길이", len );
    
    // 방법 2
     var lenfunc = (val) => val.length;
     console.log(lenfunc('hello'));
    </script>
    </head>
    <body>
    </body>
    </html>

문제5. substr

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8" />
      <title>Insert title here</title>
      <script type="text/javascript">
        function xyz(m) {
          if (typeof m === "string") {
            var x = m.substr(7, 1);
            var gender = "남";
            if (x == "2") gender = "여";
            return gender;
          } else {
            console.log("⛔️ the value is NOT of type string");
            return "";
          }
        }
    
        var gender = xyz("811025-1234567");
        console.log("성별", gender);
      </script>
    </head>
    <body></body>
    </html>

문제6. reverseString(), reverse()

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript">
      // 방법 1
     function xyz(m){
    	  var upper = m.toUpperCase();
    	  var lower = m.toLowerCase();
    	  var kkk = '';
    	  for(var i=m.length-1; i >=0; i--){
    		  kkk = kkk+ m[i];
    	  }
    	  return upper+"\t"+lower+"\t"+kkk;
     }
     var data = xyz('AbCDeF');
     console.log("데이터", data );
    
     // 방법 2) reverseString() 함수정의하고 호출
     function xyz_reverse(m){
    	  var upper = m.toUpperCase();
    	  var lower = m.toLowerCase();
        var rev_value = reverseString(m);
    	  return upper+"\t"+lower+"\t"+rev_value;
     }
     var data = xyz_reverse('AbCDeF');
     console.log("데이터", data );
    
     // 방법 3) reverse() 메서드 사용을 위한 문자열->배열->문자열
     function reverseString(str) {
      // 1. split() 메서드를 사용해 새 배열을 반환하기
      var splitString = str.split(""); // var splitString = "hello".split("");
      // ["h", "e", "l", "l", "o"]
    
      // 2. reverse() 메서드를 사용해 새 배열의 순서를 뒤집기
      var reverseArray = splitString.reverse(); // var reverseArray = ["h", "e", "l", "l", "o"].reverse();
      // ["o", "l", "l", "e", "h"]
    
      // 3. join() 메서드를 사용해 배열의 모든 요소를 문자열로 결합하기
      var joinArray = reverseArray.join(""); // var joinArray = ["o", "l", "l", "e", "h"].join("");
      // "olleh"
    
      // 4. 반전된 문자열을 반환하기
      return joinArray; // "olleh"
    }
    </script>
    </head>
    <body>
    </body>
    </html>

문제7. 배열의 합

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript">
     // 방법 1
     function sum(m){
    	  var s = 0;
    	  for(var i=0;i<m.length;i++){
    		  s = s + m[i];
    	  }
    	  return s;
     }
     var arr = [ 1, 2, 3, 4, 5];
    
     var m = sum(arr);
     console.log("합계:", m );
    
     // 방법 2
     let sum2 = (arr) => (arr.reduce((n1,n2) => (n1+n2)));
     var result = sum2(arr);
     console.log("reduce 사용 합계:", result );
    </script>
    </head>
    <body>
    </body>
    </html>

문제8. 배열 짝수의 합

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript">
     // 방법 1
     function sum(m){
    	  var s = 0;
    	  for(var i=0;i<m.length;i++){
    		 if(m[i] % 2 === 0 ){
    		  s = s + m[i];
    		 }
    	  }
    	  return s;
     }
    
     var arr = [ 1, 2, 3, 4, 5];
     var m = sum(arr);
     console.log("짝수 합계:", m );
    
     // 방법 2
     let sumEvenValue = (arr) => (
           arr.filter(val => val%2 === 0 )
              .reduce((n1,n2) => n1 + n2)
           );
     var result = sumEvenValue(arr);
     console.log("filter reduce 합계:", result );
    </script>
    </head>
    <body>
    </body>
    </html>

문제9. 배열 최대값

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8" />
      <title>Insert title here</title>
      <script type="text/javascript">
        // 방법 1
        function max(m) {
          var maxNum;
          for (var i = 0; i < m.length; i++) {
            if (maxNum == undefined) {
              maxNum = m[i];
            }
            if (maxNum < m[i]) {
              maxNum = m[i];
            }
          }
          return maxNum;
        }
    
        var arr = [11, 2, 33, 54, 5];
        var m = max(arr);
        console.log("최대값:", m);
    
        // 방법 2
        var array = [1, 10, 5, 11, 2];
    
        //최대값
        var max = array.reduce(function (previous, current) {
          return previous > current ? previous : current;
        });
    
        //최소값
        var min = array.reduce(function (previous, current) {
          return previous > current ? current : previous;
        });
    
    	  console.log('Max = ' + max);
    	  console.log('Min = ' + min);
      </script>
    </head>
    <body>
    </body>
    </html>

문제10. 배열 정렬

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript">
     // 방법 1
     function asc(m){
    	   for(var i=0;i<m.length-1;i++){
    			for(var j=0;j<m.length-1-i;j++){
    				if(m[j]>m[j+1]){
    					var temp = m[j];
    					m[j] = m[j+1];
    					m[j+1] = temp;
    				}
    			}
    		}
    	  return m;
     }
    
     var arr = [ 11, 2, 33, 54, 5];
     var m = asc(arr);
     console.log("오름차순 정렬:", m );
    
     // 방법 2
     var ascSort = arr.sort((n1,n2) => n1 -n2);
     console.log("오름차순 정렬:", ascSort);
     ascSort.forEach(val => console.log(val));
    </script>
    </head>
    <body>
    </body>
    </html>

문제11. 배열에 포함된 글자

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript">
     // 방법 1
     function bananaCheck(m){
    	//   console.log(">>1",m);
    	  var cnt = 0;
    	  for(var i=0 ; i < m.length; i++){
    		 if( m[i].includes("banana")){
    		 // if( m[i].toLowerCase().includes("banana")){
    			  cnt++;
    		  }
    	  }
    	  return cnt;
     }
    
     var arr = ['BANANA','melon','banana','apple', 'banana','bananaa'];
     var cnt = bananaCheck(arr);
     console.log("banana 글자 포함 단어 갯수:", cnt );
    
     // 방법 2) filter 사용
     let count = arr.filter(element => element.includes("banana")).length;
     console.log("banana 글자 포함 단어 갯수 filter 사용 :", count );
    
     // 방법 3) reduce 사용
     let count2 = arr.reduce((cnt, element) => cnt + (element.includes("banana")), 0);
     console.log("banana 글자 포함 단어 갯수 reduce 사용 :", count2 );
    </script>
    </head>
    <body>
    </body>
    </html>

문제12. 나이 구하기

  • 📋 코드 📋
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript">
     function myAge(m){
    	  var year = m.split("/")[0];
    	  var current = new Date().getFullYear();  
    	  var age =  current - year;
    	  return age;
     }
     
     var ssn = '1981/10/20';
     var age = myAge(ssn);
     console.log("현재 나이:", age );
    </script>
    </head>
    <body>
    </body>
    </html>

문제13. navigator (사용 중인 웹 브라우저 정보 보기)

  • 📋 코드 📋
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript">
    function info(){
    	  console.log(navigator);
    	  document.getElementById("bName").innerText=navigator.appName;
    	  document.getElementById("bVersion").value=navigator.appVersion;
    	  document.getElementById("bOnLine").innerText=navigator.onLine;
    }
    </script>
    </head>
    <body>
    <h3>사용중인 웹 브라우저 정보 보기</h3>
    	<button onclick="info()">보기</button>
    <div>
    브라우저 이름:<span id="bName"></span><br>
    브라우저 버전:<input type="text" name="bVersion" id="bVersion"><br>
    브라우저 온라인 여부:<span id="bOnLine"></span><br>
    </div>
    </body>
    </html>

문제14. locaton.href (특정 URL 접속)

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript">
       function google(){
      	 location.href="http://www.google.com";
       }
    
       function site(){
      	 var url = document.getElementById("site").value;
      	 location.href= url;
       }
    </script>
    </head>
    <body>
    <h3>자바스크립트로 특정 URL 접속하기</h3>
    <button onclick="google()">구글사이트로 가기</button><br>
    사이트주소입력:<input type="text" name="site" id="site">
    <button onclick="site()">바로가기</button>
    </body>
    </html>

문제15. 문자열 처리

  • 📋 코드 📋
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript">
    function info(){
    	  var str = document.getElementById("str").value;
    	  var str1 = str.length;
    	  var str2="";
    	  for(var i=0; i<str1; i++){
    		  str2 += str[i]+",";
    	  }
    	  var str3= str.toUpperCase();
    	  var str4 = str.toLowerCase();
    	  var str5="";
    	  for(var i=str1-1; i >= 0; i--){
    		  str5 += str[i];
    	  }
    	  var str6 = str.charAt(0);
    	  var str7 = str.charAt(2);
    	  var str8 = str.substr(0,5); // 0부터 5개 리턴
    	  //
    	  document.getElementById("str1").innerText = str1;
    	  document.getElementById("str2").innerText = str2;
    	  document.getElementById("str3").innerText = str3;
    	  document.getElementById("str4").innerText = str4;
    	  document.getElementById("str5").innerText = str5;
    	  document.getElementById("str6").innerText = str6;
    	  document.getElementById("str7").innerText = str7;
    	  document.getElementById("str8").innerText = str8;
    }
    </script>
    </head>
    <body>
    <h3>문자열 처리</h3>
    입력문자열<input type="text" name="str" id="str"><button onclick="info()">문자열 정보</button>
    <div>
    입력문자열 길이:<span id="str1"></span><br>
    입력문자:<span id="str2"></span><br>
    대문자로:<span id="str3"></span><br>
    소문자로:<span id="str4"></span><br>
    꺼꾸로 출력:<span id="str5"></span><br>
    첫글자만 출력:<span id="str6"></span><br>
    3번째 글자만 출력:<span id="str7"></span><br>
    1번째부터 5번째까지 글자만 출력:<span id="str8"></span><br>
    </div>
    </body>
    </html>

문제16. split (문자열을 배열 변환)

  • 📋 코드 📋
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript">
    function sum(){
    	  var data = document.getElementById("v1").value;
    	  var arr = data.split("/");
    	  var sum = 0;
    	  for(var i=0; i< arr.length; i++){
    		  sum += parseInt(arr[i]);
    	  }
    	  document.getElementById("result").innerText=sum;
    }
    </script>
    </head>
    <body>
    <h3>문자열 처리</h3>
    값:<input type="text" name="v1" id="v1" value="10/20/30">
    <button onclick="sum()">합계</button><br>
    합계:<span id="result"></span>
    </body>
    </html>

문제17. 배열 관리

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript">
    var arr;
    function create(){
    	arr=[];
    }
    function remove(){
    		arr=[];
    		show();
    }
    function save(){
    	  var v1 = document.getElementById("v1").value;
    	  arr.push(v1);
    	  document.getElementById("v1").value = "";
    }
    
    function show(){
    	var mesg = "";
    	for(var i=0;i<arr.length;i++){
    		mesg +=arr[i]+"<br>";
    	}
    	document.getElementById("result").innerHTML=mesg;
    }
    </script>
    </head>
    <body>
    <h3>배열 관리</h3>
    값:<input type="text" name="v1" id="v1" ><br>
    <button onclick="create()">1.배열생성</button>
    <button onclick="save()">2.배열에 값 저장</button><br>
    <button onclick="show()">3.배열에 값 출력</button>
    <button onclick="remove()">4.배열삭제</button><br>
    <div id="result"></div>
    </body>
    </html>

문제18. 합계, 평균, 중앙값

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8" />
      <title>Insert title here</title>
      <script type="text/javascript">
        function check() {
          var v1 = document.getElementById("v1").value;
          var data = v1.split(",");
          var sort = data.sort(function (a, b) {
            return a - b;
          });
          var sum = 0;
          for (var i = 0; i < sort.length; i++) {
            sum += parseInt(sort[i]);
          }
          console.log(sum);
    
          var avg = sum / sort.length;
          var median = 0;
          if (data.length % 2 === 0) {
            var n = sort.length;
            var f = parseInt(sort[n / 2 - 1]);
            var l = parseInt(sort[n / 2]);
            var i = (f + l) / 2;
            console.log(f, l, i);
            median = i;
          } else {
            var i = (sort.length + 1) / 2;
            console.log(i);
            median = parseInt(sort[i - 1]);
          }
    
          var mesg = "합계:" + sum + "<br>";
          mesg += "평균:" + avg.toFixed(2) + "<br>";
          mesg += "중앙값:" + median + "<br>";
          document.getElementById("result").innerHTML = mesg;
        }
      </script>
    </head>
    <body>
      <h3>배열 관리</h3>
      값:<input type="text" name="v1" id="v1" value="1,5,10,9,3,7,23,4,6,8" />
      <button onclick="check()">데이터 분석</button><br />
      <div id="result"></div>
    </body>
    </html>

문제19. 문자열 단어수/글자수

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript">
      function check(){
        var v1 = document.getElementById("v1").value;
    
        var data = v1.split(" ");
        var n = data.length;
        var n2=0;
        for(var i=0; i< v1.length; i++){
      	  console.log(v1[i]);
      	  if(v1[i]==" ")continue;
      	  n2++;
        }
        var mesg = "단어수:"+n+"<br>";
            mesg += "글자수:"+n2+"<br>";
    
        document.getElementById("result").innerHTML = mesg;
      }
    </script>
    </head>
    <body>
    <h3>문자열 관리</h3>
    값:<input type="text" name="v1" id="v1" value="How are you? fine thank you">
    <button onclick="check()">데이터 분석</button><br>
    <div id="result"></div>
    </body>
    </html>

문제20. 배열 오름차순/내림차순 정렬

  • 📋 코드 📋
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript">
      //배열
      var num = [10,4, 20,41, 32, 9, 1,2];
      
      function asc(){
      	var arr = num.sort(function(a,b){return a-b;});
      	document.getElementById("result").innerText=arr;
      } 
      function desc(){
      	var arr = num.sort(function(a,b){return b-a;});
      	document.getElementById("result").innerText=arr;
      } 
    </script>
    </head>
    <body>
    <h3>배열 정렬</h3>
    var num = [10,4, 20,4, 32, 9, 1,2];<br>
    <button onclick="asc()">오름차순</button>
    <button onclick="desc()">내림차순</button>
    <div id="result">
    </div>
    </body>
    </html>

문제21. onclick

  • 📋 코드 📋
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript"> 
      var arr = [];
      var n = 0;
      var cnt = 0;
      var sum = 0;
      function three(){
      	cnt++;
          n+=3;
      	arr.push(n);
      	sum+=n;
      	var mesg = "<br>클릭한 수: " + cnt;
      	    mesg += "<br>합계: " + sum;
      	document.getElementById("result").innerHTML = arr+mesg;   	
      } 
    </script>
    </head>
    <body>
    <h3>배수 출력</h3>
    <button onclick="three()">3의 배수</button>
    <div id="result">
    </div>
    </body>
    </html>

문제22. JSON 객체

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript">
      var data=[];
    
      function add(){
      	var username = document.getElementById("username").value;
      	var age = document.getElementById("age").value;
      	var address = document.getElementById("address").value;
    
      	var person={'username':username,'age':age,'address':address};
          data.push(person);
          document.getElementById("result").innerHTML="<h3>저장 완료</h3>";
      }
    
      function show(){
      	var mesg = "";
      	for(var i=0; i< data.length; i++){
      		var person = data[i];
      		mesg += (i+1)+" 번째 고객<br>";
      		mesg +="이름:"+person.username+"<br>";
      		mesg +="나이:"+person.age+"<br>";
      		mesg +="주소:"+person.address+"<br>";
      	}
      	document.getElementById("result").innerHTML=mesg;
      }
    </script>
    </head>
    <body>
    <h3>JSON 객체</h3>
    이름<input type="text" name="username" id="username"><br>
    나이<input type="text" name="age" id="age"><br>
    주소<input type="text" name="address" id="address"><br>
    <button onclick="add()">저장</button><br>
    <button onclick="show()">출력</button><br>
    <div id="result">
    </div>
    </body>
    </html>

📕 JS 미션3

문제1. document.getElementByID().value

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8" />
      <title>Insert title here</title>
      <script type="text/javascript">
        function up() {
    		var quantityObj = document.getElementById("quantity");
          var count = quantityObj.value;
          quantityObj.value = parseInt(count) + 1;
        }
    
        function down() {
          var quantityObj = document.getElementById("quantity");
          var count = quantityObj.value;
          if (count != 1) {
    			quantityObj.value = parseInt(count) - 1;
          }
        }
      </script>
    </head>
    <body>
      갯수<input type="text" name="quantity" id="quantity" value="1" />
      <button id="up" onclick="up()">+</button
      ><button id="down" onclick="down()">-</button>
    </body>
    </html>

문제2. querySelectorAll()

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8" />
      <title>Insert title here</title>
      <script type="text/javascript">
        function result() {
          var hobbies = document.querySelectorAll("input:checked");
          var mesg = "";
    
          for (let hobby of hobbies) {
            mesg = mesg + hobby.value + "\t";
          }
          // for (var i = 0; i < hobby.length; i++) {
          //   mesg = mesg + hobby[i].value + "\t";
          // }
          document.getElementById("result").innerText = mesg;
        }
      </script>
    </head>
    <body>
      <h4>취미</h4>
      <ul>
        <li>야구<input type="checkbox" name="hobby" value="야구" /></li>
        <li>농구<input type="checkbox" name="hobby" value="농구" /></li>
        <li>게임<input type="checkbox" name="hobby" value="게임" /></li>
      </ul>
      <button onclick="result()">결과보기</button><br />
      결과값:
      <div id="result"></div>
    </body>
    </html>

문제3. onkeyup

  • 📋 코드 📋
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript">
      function count(n){
      	console.log(n);
      	document.getElementById("result").innerText=n.length;
      }
    </script>
    </head>
    <body>
    글자수 세기<br>
    <textarea rows="10" cols="10" onkeyup="count(this.value)"></textarea><br>
    입력문자수:<span id="result"></span>
    </body>
    </html>

문제4. 이미지 배열

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8" />
      <title>Insert title here</title>
      <script type="text/javascript">
        //이미지 정보를 배열에 저장하여 관리
        var arr = ["a.jpg", "b.jpg", "c.jpg"];
        var idx = 0;
    
        function next() {
          var img = document.getElementById("my");
          idx++;
          if (idx == 3) idx = 2;
          img.src = arr[idx];
          imageFileName(arr[idx]);
        }
    
        function prev() {
          var img = document.getElementById("my");
          idx--;
          if (idx == -1) idx = 0;
          img.src = arr[idx];
          imageFileName(arr[idx]);
        }
    
        function imageFileName(fileName) {
          document.getElementById("result").innerText = fileName;
        }
      </script>
    </head>
    <body>
      이미지 변경하기<br />
      <img src="a.jpg" width="100" height="100" id="my" />
      <button onclick="prev()">이전</button>
    	<button onclick="next()">다음</button><br />
      이미지 파일명:<span id="result">a.jpg</span>
    </body>
    </html>

문제5. innerHTML

  • 📋 코드 📋
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8" />
      <title>Insert title here</title>
      <script type="text/javascript">
        function getName(n) {
          document.getElementById("result").innerHTML =
            "<h1>" + n.getAttribute("src") + "</h1>";
        }
      </script>
    </head>
    <body>
      이미지 이름 알아보기<br />
      <img src="a.jpg" width="100" height="100" onmouseover="getName(this)" />
      <img src="b.jpg" width="100" height="100" onmouseover="getName(this)" />
      <img
        src="c.jpg"
        width="100"
        height="100"
        onmouseover="getName(this)"
      /><br />
      파일명:<span id="result"></span>
    </body>
    </html>

문제6. document.getElementByID().src

  • 📋 코드 📋
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8" />
      <title>Insert title here</title>
      <script type="text/javascript">
        function selectImage(filename) {
          document.getElementById("myImg").src = filename;
        }
      </script>
    </head>
    <body>
      이미지선택하기<br />
      <select onchange="selectImage(this.value)">
        <option>a.jpg</option>
        <option>b.jpg</option>
        <option>c.jpg</option>
      </select>
      <img src="a.jpg" width="100" height="100" id="myImg" />
    </body>
    </html>

문제7. 비밀번호 확인

  • 📋 코드 📋
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript">
      function pwcheck(pw1){
      	var mesg = "비밀번호 일치";
      	var pw = document.getElementById("passwd").value;
      	if(pw1 != pw){
      		mesg = "비밀번호 불일치";
      	}
      	document.getElementById("result").innerText = mesg;
      }
    </script>
    </head>
    <body>
    비밀번호 확인 구현<br>
    비밀번호<input type="text" name="passwd" id="passwd"><br>
    비밀번호 재확인<input type="text" name="passwd1" id="passwd1" onkeyup="pwcheck(this.value)">
    <span id='result'></span>
    </body>
    </html>

문제8. 전체 선택

  • 📋 코드 📋
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8" />
      <title>Insert title here</title>
      <script type="text/javascript">
        function chk(selectedCheckbox) {
          var checkboxes = document.querySelectorAll(".lang");
    		for(let checkbox of checkboxes){
    			checkbox.checked = selectedCheckbox.checked;
    		}
          // for (var i = 0; i < lang.length; i++) {
          //   lang[i].checked = n.checked;
          // }
        }
      </script>
    </head>
    <body>
      전체선택
      <input type="checkbox" name="all" onclick="chk(this)" /><br />
      <input type="checkbox" name="java" class="lang" />java<br />
      <input type="checkbox" name="sql" class="lang" />sql<br />
      <input type="checkbox" name="angular" class="lang" />angular<br />
    </body>
    </html>

문제9. font-size

  • 📋 코드 📋
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8" />
      <title>Insert title here</title>
      <script type="text/javascript">
        function chk(m) {
          var resultDiv = document.getElementById("result");
          resultDiv.style = "font-size:" + m;
        }
      </script>
    </head>
    <body>
      글꼴크기:
      <select onchange="chk(this.value)">
        <option>16px</option>
        <option>32px</option>
        <option>40px</option>
        <option>56px</option>
      </select>
      <div id="result">안녕하세요.</div>
    </body>
    </html>

문제10. 값 미입력시 경고창 (alert)

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8" />
      <title>Insert title here</title>
      <script type="text/javascript">
        function login() {
          var id = document.getElementById("userid");
          var pw = document.getElementById("passwd");
    
          if (id.value.length == 0) {
            alert("아이디값을 입력하시오");
            id.focus();
            return false;
          }
          if (pw.value.length == 0) {
            alert("비밀번호값을 입력하시오");
            pw.focus();
            return false;
          }
        }
      </script>
    </head>
    <body>
      <form action="success.html" onSubmit="return login()">
        아이디<input type="text" name="userid" id="userid" /><br />
        비밀번호<input type="text" name="passwd" id="passwd" /><br />
        <input type="submit" value="로그인" />
      </form>
    </body>
    </html>

문제11. window.open

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript">
     var childWin;
     function childOpen(){
    	   childWin = window.open("childWin.html","","width=200,height=200");
     }
     function childClose(){
    	   childWin.close();
     }
     function parentClose(){
    	   window.close();
     }
    </script>
    </head>
    <body>
    <button onClick="childOpen()">새창 열기</button>
    <button onClick="childClose()">새창 닫기</button>
    <button onClick="parentClose()">현재창(부모장) 닫기</button>
    </body>
    </html>
  • 📋 childWin.html 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script>
    function a(){
    	 window.close();
    }
    
    function b(){
    	 opener.close();
    }
    </script>
    </head>
    <body>
    childWin.html<br>
    <button onClick="a()">현재창 닫기</button>
    <button onClick="b()">부모창 닫기</button>
    </body>
    </html>

문제12. 아이디 중복 검사

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript">
     var childWin;
     function idCheck(){
    	   childWin = window.open("childWin2.html","","width=200,height=200");
     }
    </script>
    </head>
    <body>
    아이디<input type="text" name="userid" id="userid" readonly>
    <button onClick="idCheck()">아이디중복</button>
    </body>
    </html>
  • 📋 childWin2.html 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script>
    function a(){
    
    	 var data = document.getElementById("userid").value;
    	 opener.document.getElementById("userid").value = data;
    	 window.close();
    }
    </script>
    </head>
    <body>
    아이디:<input type="text" name="userid" id="userid">
    <button onClick="a()">아이디 사용 가능</button>
    </body>
    </html>

문제13. 주소 추가

  • 📋 코드 📋
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8" />
      <title>Insert title here</title>
      <script type="text/javascript">
        var childWin;
        function idCheck() {
          childWin = window.open("childWin3.html", "", "width=400,height=400");
        }
      </script>
    </head>
    <body>
      우편번호<input type="text" name="post" id="post" /><br />
      주소:<input type="text" name="address" id="address" /><br />
      추가주소:<input type="text" name="address1" id="address1" />
      <button onClick="idCheck()">주소</button>
    </body>
    </html>
  • 📋 childWin3.html 코드 📋
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script>
    function post(postNum,addr){
    	console.log("post");
    	// console.log(opener.document.getElementById("post").value);
    	 opener.document.getElementById("post").value = postNum;
    	 opener.document.getElementById("address").value = addr;
    	 window.close();
    }
    function aaa(){
    	 console.log("aaa");
    }
    </script>
    </head>
    <body>
    <table border="1">
       <tr>
        <th>우편번호</th>
        <th>주소</th>
      </tr>
      <tr>
        <td><a href="javascript:post('12345','서울시 강남구 XXX 아파트')">12345</a></td>
        <td>서울시 강남구 XXX 아파트</td>
      </tr>
      <tr>
        <td><a href="javascript:post('99999','경기도 고양시 ZZZ 아파트')">99999</a></td>
        <td>경기도 고양시 ZZZ 아파트</td>
      </tr>
    </table>
    </body>
    </html>

문제14. 입력 값 누적 저장, enter 키

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript">
     var arr = [];
     function save(){
    	   var v1 = document.getElementById("v1").value;
    	   arr.push(v1);
    
    	   list();
     }
    
     function list(){
    	   var result = document.getElementById("result");
    	   var mesg = '';
    	   for(var i=0; i < arr.length; i++){
    		   mesg = mesg + arr[i]+"<br>";
    	   }
    	   result.innerHTML=mesg;
     }
    
     function enter(e){
    	   if(e.keyCode == 13){
    		   save();
    	   }
     }
    </script>
    </head>
    <body>
    값:<input type="search" name="v1" id="v1" onkeyup="enter(event)">
    <div id="result">
    </div>
    </body>
    </html>

문제15. 다양한 연산

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript">
    function sum(){
    	  var v1 = document.getElementById("v1").value;
    	  var v2 = document.getElementById("v2").value;
    	  var result = document.getElementById("result");
    	  result.value = parseInt(v1) + parseInt(v2);
    }
    
     function total(){
    	   var price = document.getElementById("price").value;
    	   var quantity = document.getElementById("quantity").value;
    	   var total = document.getElementById("total");
    	   total.innerText = parseInt(price) * parseInt(quantity);
     }
    
     function totalPrice(){
    	   var fruit = document.querySelectorAll(".fruit");
    	   var total=0;
    	   for(var i=0 ;i < fruit.length;i++){
    		   if(fruit[i].checked){
    			   total += parseInt(fruit[i].value);
    		   }
    	   }
    	   var totalPrice = document.getElementById("totalPrice");
    	   totalPrice.innerText = total;
     }
    </script>
    </head>
    <body>
    <h3>1. + 연산</h3>
    <input type="text" name="v1" id="v1" value="10">+
    <input type="text" name="v2" id="v2" value="20">=
    <input type="text" name="result" id="result" value="" readonly>
    <button onclick="sum()">연산</button><br>
    <h3>2. 총합 구하기</h3>
    가격<input type="text" name="price" id="price" value="2500"> X
    수량<select id="quantity" onchange="total()">
       <option>1</option>
       <option>2</option>
       <option>3</option>
       <option>4</option>
       <option>5</option>
     </select>
    총합:<span id="total"></span>
    <h3>3. 총합 구하기2 ( 선택된 값만 )</h3>
    <div>
    바나나(1000원)<input type="checkbox" name="fruit" class="fruit" value="1000"><br>
    사과(500원)<input type="checkbox" name="fruit" class="fruit" value="500"><br>
    배(1500원)<input type="checkbox" name="fruit" class="fruit" value="1500">
    <button onclick="totalPrice()">총합구하기</button><br>
    선택한 총가격:<span id="totalPrice"></span>
    </div>
    </body>
    </html>

📒 jQuery

📕 jQuery 미션1

문제1. $(selector).val()

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
    	$(document).ready(function() {
    
    		$("#up").on("click", function() {
    			var count = $("#quantity").val();
    			$("#quantity").val(parseInt(count) + 1);
    		});
    		$("#down").on("click", function() {
    			var count = $("#quantity").val();
    			if (count != 1) {
    				$("#quantity").val(parseInt(count) - 1);
    			}
    		});
    	});
    </script>
    </head>
    <body>
    	갯수
    	<input type="text" name="quantity" id="quantity" value="1">
    	<button id="up">+</button>
    	<button id="down">-</button>
    </body>
    </html>

문제2. $(this).val().length

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
    
    	   $("textarea").on("keyup", function() {
    
    		     $("#result").text($(this).val().length);
    	   });
    
    	});
    </script>
    </head>
    <body>
    글자수 세기<br>
    <textarea rows="10" cols="10"></textarea><br>
    입력문자수:<span id="result"></span>
    </body>
    </html>

문제3. $(image).attr("src", 이미지)

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
        //이미지 정보를 배열에 저장하여 관리
        var arr = ["a.jpg","b.jpg", "c.jpg"];
        var idx = 0;
        $(document).ready(function() {
    
      	   $("#prev").on("click", function() {
      		   idx--;
      		   if(idx==-1)idx=0;
    	    	  $("img").attr("src", arr[idx]);
    	    	  $("result").text(arr[idx]);
      	   });
      	   $("#next").on("click", function() {
      		      idx++;
      	    	  if(idx==3)idx=2;
      	    	  $("img").attr("src", arr[idx]);
      	    	  $("result").text(arr[idx]);
      	   });
      	});
    </script>
    </head>
    <body>
    이미지 변경하기<br>
    <img src="a.jpg" width="100" height="100" id="my">
    <button id="prev">이전</button><button id="next">다음</button><br>
    이미지 파일명:<span id="result">a.jpg</span>
    </body>
    </html>

문제4. $(this).attr("src")

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
       $(document).ready(function() {
    
     	   $("img").on("mouseover", function() {
    
     		     $("#result").html("<h1>"+$(this).attr("src")+"</h1>");
     	   });
    
     	});
    </script>
    </head>
    <body>
    이미지 이름 알아보기<br>
    <img src="a.jpg" width="100" height="100" >
    <img src="b.jpg" width="100" height="100" >
    <img src="c.jpg" width="100" height="100" ><br>
    파일명:<span id="result"></span>
    </body>
    </html>

문제5. $(image).attr("src", $(this).val())

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
       $(document).ready(function() {
    
       	   $("select").on("change", function() {
    
       		     $("img").attr("src",$(this).val());
       	   });
    
       	});
    </script>
    </head>
    <body>
    이미지선택하기<br>
    <select>
    <option>a.jpg</option>
    <option>b.jpg</option>
    <option>c.jpg</option>
    </select>
    <img src="a.jpg" width="100" height="100" id="my">
    </body>
    </html>

문제6. 비밀번호 확인

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
    
    	   $("#passwd1").on("keyup", function() {
    
    		 var mesg = "비밀번호 일치";
       	var pw = $("#passwd").val();
       	var pw1 = $(this).val();
       	if(pw1 != pw){
       		mesg = "비밀번호 불일치";
       	}
       	$("#result").text(mesg);
    	   });
    
    	});
    </script>
    </head>
    <body>
    비밀번호 확인 구현<br>
    비밀번호<input type="text" name="passwd" id="passwd"><br>
    비밀번호 재확인<input type="text" name="passwd1" id="passwd1">
    <span id='result'></span>
    </body>
    </html>

문제7. font-color

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
    
    	$("#up").on("click", function() {
    
    		$("#result").css({"font-size":"32px","color":"red"});
    
    	});
    	$("#down").on("click", function() {
    		$("#result").css({"font-size":"16px","color":"blue"});
    	});
    });
    </script>
    <body>
    	<button id="up">+</button>
    	<button id="down">-</button>
    	<div id="result">안녕하세요.</div>
    </body>
    </html>

문제8. font-size

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script
    	src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
    		$("select").on("change", function() {
    			$("#result").css("font-size", $(this).val());
    
    		});
    	});
    </script>
    </head>
    <body>
    글꼴크기:
    <select>
    <option>16px</option>
    <option>32px</option>
    <option>40px</option>
    <option>56px</option>
    </select>
    <div id="result">
     안녕하세요.
    </div>
    </body>
    </html>

문제9. focus()

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script
    	src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
    
    	   $("#ssn1").on("keyup",function(e){
    		  if(this.value.length==6){
    			  $("#ssn2").focus();
    		  } 
    	   });
    
    });
    </script>
    </head>
    <body>
    주민번호:
    <input type="text" name="ssn1" id="ssn1">-
    <input type="text" name="ssn2" id="ssn2">
    </body>
    </html>

문제10. trigger

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
    
    	  $("#x").on("click",function(){
    		  $("#result").text($("input").val().length);
    	  });
    	  
    	  $("input").on("keyup" , function(e){
    		 $("#x").trigger("click"); 
    	  });
    
    });
    </script>
    </head>
    <body>
    값:<input type="text"><button id="x">글자수 얻기</button><br>
    글자수:<span id="result"></span>
    </body>
    </html>

📕 jQuery 미션2

문제1. $(selector).each()

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
     $(document).ready(function() {
    
    	   $("button").on("click", function() {
    		   var mesg="";
    		     $("input:checked").each(function(idx,data){
    		    	 mesg = mesg + $(this).val()+ "\t";
    		     });
    		     $("#result").text(mesg);
    	   });
    
    	});
    </script>
    </head>
    <body>
    취미<br>
    <ul>
    <li>야구<input type="checkbox" name="hobby" value="야구"></li>
    <li>농구<input type="checkbox" name="hobby" value="농구"></li>
    <li>게임<input type="checkbox" name="hobby" value="게임"></li>
    </ul>
    <button>결과보기</button><br>
    결과값:<div id="result"></div>
    </body>
    </html>

문제2. 전체 선택

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
     $(document).ready(function() {
    
     	   $("#all").on("click", function() {
     		     var result = this.checked;
     		     $(".lang").each(function(idx,data){
     		    	 this.checked = result;
     		     });
     	   });
    
     	});
    </script>
    </head>
    <body>
    전체선택
    <input type="checkbox" name="all" id="all"><br>
    <input type="checkbox" name="java" class="lang">java<br>
    <input type="checkbox" name="sql" class="lang">sql<br>
    <input type="checkbox" name="angular" class="lang">angular<br>
    </body>
    </html>

문제3. 값 미입력시 경고창 (alert)

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
    		$("form").on("submit", function(e) {
    
    			var id = $("#userid");
    			var pw = $("#passwd");
    
    			if(id.val().length==0){
    	    		alert("아이디값을 입력하시오");
    	    	 id.focus();
    	    		return false;
    	    	}
    	    	if(pw.val().length==0){
    	    		alert("비밀번호값을 입력하시오");
    	    		pw.focus();
    	    		return false;
    	    	}
    
    		});
    	});
    </script>
    </head>
    <body>
    <form action="success.html">
    아이디<input type="text" name="userid" id="userid"><br>
    비밀번호<input type="text" name="passwd" id="passwd"><br>
    <input type="submit" value="로그인" >
    </form>
    </body>
    </html>

문제4. window.open

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script
    	src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
     $(document).ready(function() {
    
    	   var childWin;
    		$("#one").on("click", function(e) {
    			childWin = window.open("childWin.html","","width=200,height=200");
    		});
    		$("#two").on("click", function(e) {
    			childWin.close();
    		});
    		$("#three").on("click", function(e) {
    			window.close();
    		});
    	});
    </script>
    </head>
    <body>
    <button id="one">새창 열기</button>
    <button id="two">새창 닫기</button>
    <button id="three">현재창(부모장) 닫기</button>
    </body>
    </html>
  • 📋 childWin.html 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script
    	src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
    $(document).ready(function() {
    
    		$("#a").on("click", function(e) {
    			window.close();
    		});
    		$("#b").on("click", function(e) {
    			opener.close();
    		});
    
    	});
    </script>
    </head>
    <body>
    childWin.html<br>
    <button id="a">현재창 닫기</button>
    <button id="b">부모창 닫기</button>
    </body>
    </html>

문제5. 아이디 중복 검사

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script
    	src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
    	 var childWin;
    		$("button").on("click", function(e) {
    			 childWin = window.open("childWin2.html","","width=200,height=200");
    		});
    	   });
    </script>
    </head>
    <body>
    아이디<input type="text" name="userid" id="userid">
    <button>아이디중복</button>
    </body>
    </html>
  • 📋 childWin2.html 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script
    	src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
    $(document).ready(function() {
    
    		$("#a").on("click", function(e) {
    			 opener.$("#userid").val($("#userid").val());
    			 window.close();
    		});
    });
    </script>
    </head>
    <body>
    아이디:<input type="text" name="userid" id="userid">
    <button id="a">아이디 사용 가능</button>
    </body>
    </html>

문제6. 주소 추가

  • 📋 코드 📋
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script	src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
     $(document).ready(function() {
    		 var childWin;
    			$("button").on("click", function(e) {
    				childWin = window.open("childWin3.html","","width=400,height=400");
    			});
     });
    </script>
    </head>
    <body>
    우편번호<input type="text" name="post" id="post"><br>
    주소:<input type="text" name="address" id="address"><br>
    추가주소:<input type="text" name="address1" id="address1">
    <button>주소</button>
    </body>
    </html>
  • 📋 childWin3.html 코드 📋
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script
    	src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
    function post(postNum,addr){
    	 opener.$("#post").val(postNum);
    	 opener.$("#address").val(addr);
    	 window.close();
    }
    </script>
    </head>
    <body>
    <table border="1">
       <tr>
        <th>우편번호</th>
        <th>주소</th>
      </tr>
      <tr>
        <td><a href="javascript:post('12345','서울시 강남구 XXX 아파트')">12345</a></td>
        <td>서울시 강남구 XXX 아파트</td>
      </tr>
      <tr>
        <td><a href="javascript:post('99999','경기도 고양시 ZZZ 아파트')">99999</a></td>
        <td>경기도 고양시 ZZZ 아파트</td>
      </tr>
    </table>
    </body>
    </html>

문제7. 입력 값 누적 저장, enter 키

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script
    	src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
     var arr = [];
     function save(){
    	   var v1 = $("#v1");
    	   arr.push(v1.val());
    	   list();
     }
    
     function list(){
    	   var result = $("#result");
    	   var mesg = '';
    	   $.each(arr,function(idx,ele){
    		   mesg = mesg + arr[idx]+"<br>";
    	   });
    	   result.html(mesg);
     }
    
     $(document).ready(function() {
    		$("#v1").on("keyup", function(e) {
    			if(e.keyCode == 13){
    				   save();
    			   }
    		});
    });
    </script>
    </head>
    <body>
    값:<input type="search" name="v1" id="v1">
    <div id="result">
    </div>
    </body>
    </html>

문제8. 다양한 연산

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script
    	src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
     $(document).ready(function() {
    		$("#one").on("click", function(e) {
    			  var v1 = $("#v1").val();
    			  var v2 = $("#v2").val();
    			  $("#result").val(parseInt(v1)+parseInt(v2));
    		});
    
    		$("#quantity").on("change", function(e) {
    			  var price = $("#price").val();
    			  var quantity = $("#quantity").val();
    			  $("#total").text(parseInt(price) * parseInt(quantity));
    		});
    
    		$("#two").on("click", function(e) {
    
    			 var total = 0;
    			 $(".fruit").each(function(idx,ele){
    				 if(ele.checked){
    					 total += parseInt($(this).val());
    				 }
    			 });
    
    			 $("#totalPrice").text(total);
    		});
    
    });
    </script>
    </head>
    <body>
    <h3>1. + 연산</h3>
    <input type="text" name="v1" id="v1" value="10">+
    <input type="text" name="v2" id="v2" value="20">=
    <input type="text" name="result" id="result" value=""><button id="one">연산</button><br>
    <h3>2. 총합 구하기</h3>
    가격<input type="text" name="price" id="price" value="2500"> X
    수량<select id="quantity">
       <option>1</option>
       <option>2</option>
       <option>3</option>
       <option>4</option>
       <option>5</option>
     </select>
    총합:<span id="total"></span>
    <h3>3. 총합 구하기2 ( 선택된 값만 )</h3>
    <div>
    바나나(1000원)<input type="checkbox" name="fruit" class="fruit" value="1000"><br>
    사과(500원)<input type="checkbox" name="fruit" class="fruit" value="500"><br>
    배(1500원)<input type="checkbox" name="fruit" class="fruit" value="1500">
    <button id="two">총합구하기</button><br>
    선택한 총가격:<span id="totalPrice"></span>
    </div>
    </body>
    </html>

문제9. li 태그 합계

  • 📋 코드 📋
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
    	var sum = 0;
    	  $("button").on("click",function(event){
    		  $("li").each(function(idx,ele){
    				sum += parseInt($(this).text());
    			})
    			$("#result").text(sum);
    	  });
    });
    </script>
    </head>
    <body>
    	<ul>
    	 <li>5</li>
    	 <li>15</li>
    	 <li>25</li>
    	 <li>35</li>
    	 <li>45</li>
    	 <li>55</li>
    	 <li>65</li>
    	</ul>
    <button id="sum">li태그의 총합계</button><br>
    합계:<span id="result"></span>
    </body>
    </html>

문제10. li 태그 css

  • 📋 코드 📋
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script
          src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
        $("li:nth-child(2n)").css({"color":"red" , "font-size":"30px"});
         var sum = 0;
         $("#sum").on("click",function(event){
              $("li").each(function(idx,ele){
                  if(idx%2 != 0)
                    sum += parseInt($(this).text());
                })
                $("#result").text(sum);
          });
    });
    </script>
    </head>
    <body>
    	<ul>
    	 <li>5</li>
    	 <li>15</li>
    	 <li>25</li>
    	 <li>35</li>
    	 <li>45</li>
    	 <li>55</li>
    	 <li>65</li>
    	</ul>
    <button id="sum">li태그의 총합계</button><br>
    합계:<span id="result"></span>
    </body>
    </html>

문제11. ajax

  • 📋 코드 📋

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function(){
          $("#req").on("click",function(event){
          	//ajax코드
    			var targetDt= $("#targetDt").val();
          	$.ajax({
          		type:"get",
          		url:"http://www.kobis.or.kr/kobisopenapi/webservice/rest/boxoffice/searchDailyBoxOfficeList.json?key=3d430a039fb1bae3fe5f0bc48df64e46&targetDt="+targetDt,
          		dataType:"json",
          		success:function(responseData, status, xhr){
    
    					var dailyBoxOfficeList = responseData.boxOfficeResult.dailyBoxOfficeList;
    					var table = `<table border="1">
    						          <tr>
    									<th>순위</th>
    									<th>제목</th>
    									<th>개봉일</th>
    									<th>상영횟수</th>
    								  </tr>
    						        `;
    					$.each(dailyBoxOfficeList, function(idx, daily){
    						 table +=`
    						         <tr>
    									<td>${daily.rank}</td>
    									<td>${daily.movieNm}</td>
    									<td>${daily.openDt}</td>
    									<td>${daily.showCnt}</td>
    								  </tr>
    						        `;
    					});
    					table +=`</table>`;
    
    					$("#result").html(table);
          		},
          		error:function(xhr,status,e){
          			console.log(status, e);
          		}
          	});
          });
      });
    </script>
    </head>
    <body>
    <h1>박스오피스 순위</h1>
    <input type="text" name="targetDt" id="targetDt" placeholder="입력포맷:20230101">
    <button id="req">요청</button>
    <div id="result"></div>
    </body>
    </html>
profile
Notion으로 이동 (https://24tngus.notion.site/3a6883f0f47041fe8045ef330a147da3?v=973a0b5ec78a4462bac8010e3b4cd5c0&pvs=4)

0개의 댓글