JavaScript 四則演算プログラム例

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Calc</title>
<script>
window.addEventListener('load', function() {
    var selA = document.getElementById('selA');
    var tboxA = document.getElementById('tboxA');
    var tboxB = document.getElementById('tboxB');
    var tboxC = document.getElementById('tboxC');
    var btnA = document.getElementById('btnA');

    btnA.onclick = function () {
        if (isNaN(tboxA.value))
        {
            alert("数値を入力して下さい。");
            return;
        }
        if (isNaN(tboxA.value))
        {
            alert("数値を入力して下さい。");
            return;
        }

        switch (selA.value)
        {
            case '+':
                tboxC.value = (Number(tboxA.value) + Number(tboxB.value));
                break;
            case '-':
                tboxC.value = (Number(tboxA.value) - Number(tboxB.value));
                break;
            case '×':
                tboxC.value = (Number(tboxA.value) * Number(tboxB.value));
                break;
            case '÷':
                if (Number(tboxB.value) == 0)
                {
                    alert("'0'で除算することは出来ません");
                } else {
                    tboxC.value = (Number(tboxA.value) / Number(tboxB.value));
                }
                break;
        }
    }
}, false);
</script>
</head>
<body>
    <div class="PRT" id="PRT_A">
        <p class="CLB">Calc</p>
    </div>
    <div class="PRT" id="PRT_B">
        <form name="fromA" id="frmA">
            <p>
            <input type="text name="tboxA" id="tboxA" size="3" value="0">

            <select name="selA" id="selA">
                <option value="+" selected>+</option>
                <option value="-">-</option>
                <option value="×">×</option>
                <option value="÷">÷</option>
            </select>
            <input type="text name="tboxB" id="tboxB" size="3" value="0">
            </p>
            <p>
            <input type="button" name="btnA" id="btnA" value="計算">
            </p>
            <p>
            <input type="text name="tboxC" id="tboxC" size="3" value="0">
            </p>
        </form>
    </div>
</body>
</html>

 

Calc.html
HTMLドキュメント 2.3 KB
Calc仕様書.ods
Open Office Spreadsheet(表計算) 9.5 KB