고래씌

[JavaScript] 계산 실습문제 본문

Front-End/JavaScript

[JavaScript] 계산 실습문제

고래씌 2023. 11. 9. 13:44

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>1_기본문법_계산</title>
    <!-- <style>
        .warnning{
            background-color : "white";
            color : "black";
        }
    </style> -->
</head>
<body>
    <h1>Practice2</h1>

    <input type="text" size="5" id="num1">
    <select name="calc" id="calc" onchange="changFn(this)">
        <option name ="calc" value="+">+</option>
        <option name ="calc" value="-">-</option>
        <option name ="calc" value="*">*</option>
        <option name ="calc" value="/">/</option>
        <option name ="calc" value="%">%</option>
    </select>
    <input type="text" size="5" id="num2">
    <button onclick="click2();">=</button>
    <input type="text" id="result" size="5" class="warnning" readonly>

    <script>
        function click2() {
            var num1 = document.getElementById("num1").value;
            var num2 = document.getElementById("num2").value;

            // 방법 1. 
            var calc = changFn(document.getElementsByName("calc")[0]);

            // 방법 2.
            // const calc = changFn(document.querySelector("#calc"));

            console.log(calc);

  

            switch(calc){
            case '+' : var result1 = Number(num1) + Number(num2); break;
            case '-' : var result1 = Number(num1) - Number(num2); break;
            case '*' : var result1 = parseFloat(num1) * Number(num2); break;
            case '/' : var result1 = Number(num1) / Number(num2); break;
            case '%' : var resutl1 = Number(num1) % Number(num2); break;
            }

            if(isNaN(result1) || result1 == Infinity || result1 == -Infinity){
                // result2.className="warnning";
                result.style.borer = "3px outset gray";
                result.style.backgroundColor = "red";
                result.style.color = "white";
                result.value = "연산불가";
                return;
            
            }else{
                result.style.backgroundColor = "white";
                result.style.color = "black";
            }
            console.log(result1);
            result.value = result1;
        }

        function changFn(target){

            const value = target.value;
            
            return value;
        }


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

'Front-End > JavaScript' 카테고리의 다른 글

[JavaScript] 6-2. 배열 반복문  (0) 2023.11.10
[JavaScript] 6-1. 배열  (1) 2023.11.09
[JavaScript] 체크박스 실습문제  (0) 2023.11.09
[JavaScript] 5. 문자열과 숫자  (0) 2023.11.08
[JavaScript] 4. 변수와 자료형  (0) 2023.11.08