15: Exercises in JavaScript | Create a Calculator Using JavaScript | JavaScript Tutorial | mmtuts




Exercises in JavaScript | Create a Calculator Using JavaScript | JavaScript Tutorial | mmtuts. In this JavaScript tutorial you will create your first JavaScript exercise. The exercise will be building a calculator using JavaScript which is a very good and simply project to start out with.

➤ GET ACCESS TO MY LESSON MATERIAL HERE!

First of all, thank you for all the support you have given me!

I am really glad to have such an awesome community on my channel. It motivates me to continue creating and uploading content! So thank you!

I am now using Patreon to share improved and updated lesson material, and for a small fee you can access all the material. I have worked hard, and done my best to help you understand what I teach.

I hope you will find it helpful 🙂

Material for this lesson: https://www.patreon.com/posts/javascript-15-18708464

Original source


36 responses to “15: Exercises in JavaScript | Create a Calculator Using JavaScript | JavaScript Tutorial | mmtuts”

  1. If you want to get result on the main screen other than inner window then you can use this statement in your code document.getElementById("result").innerHTML = Answer; and make a div in HTML page as well 😛

  2. Why is it when I alert the value of a and b to say what the values are, it still shows as NaN(not a number) even though its been given the parseInt method???

    Alert( "value 1 =" + a + "value 2 = +b);
    //This page says
    Value 1 = NaN value 2 = NaN

  3. for class debate, a little changed:
    html:

    <body>
    <form>
    <!– type="number" -> so letters can not be Enterd –>
    value1: <input type="number" id="val1"><br>
    value2: <input type="number" id="val2"><br>
    operator:
    <select id="operator">
    <option value="add">Add</option>
    <option value="subtruct">Subtruct</option>
    <option value="mul">Multiply</option>
    <option value="divide">Divide</option>
    <!– added power option –>
    <option value="pow">Power</option>
    </select>
    <button type="button" onclick="calc()">Calculate</button>
    </form>
    <div>
    <!– result in an expected location –>
    <p>Result: <span id="result"></span></p>
    </div>
    <script src=" js/main.js"> </script>
    </body>

    js:

    function calc() {
    var a = parseInt(document.querySelector('#val1').value);
    var b = parseInt(document.querySelector('#val2').value);
    var oper = document.querySelector('#operator').value;

    var calculate;

    if (oper == 'add') {
    calculate = a + b;
    } else if (oper == 'subtruct') {
    calculate = a – b;
    } else if (oper == 'mul') {
    calculate = a * b;
    } else if (oper == 'pow') {
    calculate = a ** b;
    } else {
    calculate = a / b;
    }
    document.querySelector('#result').innerHTML = calculate;
    console.log(calculate);
    }

Leave a Reply