JS/JS 예시

[JS] 주민번호를 넣고 버튼을 누르면, 생년월일 / 성별 / 나이 출력

congs 2023. 4. 13. 15:56

 

나이구하기 이름 :
주민번호 :

 

 

 

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>나이구하기</title>
    <!-- 이름과 주민번호를 넣고 버튼을 누르면, 이름/ 생년월일 / 성병 / 나이 출력하기 -->
</head>
<body>
    이름 : <input type="text" id="name"> <br>
    주민번호 : <input type="text" id="rNum"> <br>
    <button type="button" onclick="button();">확인</button>

    <h3 id="result"></h3>
    <!-- 이름, 생년월일, 성별, 나이 출력 -->

     <script>
        
        function button() {
            // 이름, 주민등록번호 가져오기
            let name = document.getElementById('name').value;
            let rNum = document.getElementById('rNum').value;
            
            // 생년월일 추출
            let birth = rNum.substring(0,rNum.indexOf('-'));
            
            // 성별 추출
            let gender =
            (rNum.charAt(rNum.indexOf('-')+1)%2==1)? '남자': '여자';    
            
            // 나이 추출 (형변환 필요)
            let now = Number(new Date().getFullYear()); // 현재 날짜의 연도
            let age = Number(birth.slice(0,2)); // 입력생년월일 중 생년만 
            let finalAge =
            (rNum.charAt(rNum.indexOf('-')+1)== 1 || rNum.charAt(rNum.indexOf('-')+1) == 2)?
            now - (1900+age) : now - (2000+age);
           
            // h3에 출력
            document.getElementById('result').innerText = 
            `이름: ${name}, 생년월일: ${birth}, 성별: ${gender}, 나이: ${finalAge}`
        }
     </script>


</body>

'JS > JS 예시' 카테고리의 다른 글

[JS] 구구단 출력 (이중반복문 while)  (0) 2023.04.14
[JS] 제곱 구하기 (while문 이용)  (0) 2023.04.14
[JS] 2023-04-13 (목) 출력  (0) 2023.04.13
[JS] 성적 계산기  (0) 2023.04.13
[JS] Object 생성하고 출력해보기  (0) 2023.04.12