function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
WonJeungWonJeung 

Simple calculator using Lightning Components

Hello, I'm new to Lightning Components and I decided to create a calculator using Lightning Components.
Given two numbers, when I click "Add" the result should be displayed.

Here's the code:

calculator.cmp
<aura:component >
    <aura:attribute name = 'num1' type = 'Integer' default = '15'></aura:attribute>
    <aura:attribute name = 'num2' type = 'Integer' default = '20'></aura:attribute>
    <aura:attribute name = 'sum' type = 'Integer'></aura:attribute>
    <div>
        <p>Add</p><lightning:button label = 'Add' onClick = '{!c.add}'/>
        <p>{!v.num1} + {!v.num2} = {!v.sum}</p>
    </div>
</aura:component>

calculatorController.js
({
    add : function(component, event, helper) {     
        //Add numbers
        var num1 = component.get('v.num1');
        var num2 = component.get('v.num2');
        var sumResult = num1 + num2;
        component.set('v.sum', sumResult);
        
    }
})

The add result doesn't show up when I click the button. It'd be great if someone helps! Thanks!
Best Answer chosen by WonJeung
Ajay K DubediAjay K Dubedi
Hi WonJeung,
Change your onClick - > onclick.  In your case the controller method was not fire.
Please try below code it works fine for me and let me know if this works for you. If still need modifications do let me know.

Component :
<aura:component >
    <aura:attribute name = 'num1' type = 'Integer' default = '15'></aura:attribute>
    <aura:attribute name = 'num2' type = 'Integer' default = '20'></aura:attribute>
    <aura:attribute name = 'sum' type = 'Integer'></aura:attribute>
    <div>
        <p>Add</p><lightning:button label = 'Add' onclick = '{!c.addMethod}'/>
        <p>{!v.num1} + {!v.num2} = {!v.sum}</p>
    </div>
</aura:component>



Controller :
 
({
    addMethod : function(component, event, helper) {     
        //Add numbers
        var num1 = component.get("v.num1");
        var num2 = component.get("v.num2");
        console.log(num1);
        console.log(num2);
        var sumResult = num1 + num2;
        component.set('v.sum', sumResult);
        
    }
})



I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi

All Answers

Khan AnasKhan Anas (Salesforce Developers) 
Hi Won,

Greetings to you!

Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.

Component:
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    
    <aura:attribute name="num1" type="integer" />
    <aura:attribute name="num2" type="integer" />
    <aura:attribute name="total" type="integer" />
    
    <aura:attribute name="isAdd" type="boolean" default="false" />
    <aura:attribute name="isSub" type="boolean" default="false" />
    <aura:attribute name="isMul" type="boolean" default="false" />
    <aura:attribute name="isDiv" type="boolean" default="false" />
    
    <lightning:input name="input1" label="Enter First Number" value="{!v.num1}" />
    <lightning:input name="input2" label="Enter Second Number" value="{!v.num2}" />
    <br/>
    <lightning:buttonGroup>
        <lightning:button label="Addition" onclick="{!c.Add}" />
        <lightning:button label="Subtract" onclick="{!c.Sub}" />
        <lightning:button label="Multiply" onclick="{!c.Mul}" />
        <lightning:button label="Division" onclick="{!c.Divi}" />
        <lightning:button label="Clear" onclick="{!c.Clear}" />
    </lightning:buttonGroup>
    
    <br/>
    
    <aura:if isTrue="{!v.isAdd}">
        Addition of Two Numbers = {!v.total}
    </aura:if>
    <aura:if isTrue="{!v.isSub}">
        Subtraction of Two Numbers = {!v.total}
    </aura:if>
    <aura:if isTrue="{!v.isMul}">
        Multiplication of Two Numbers = {!v.total}
    </aura:if>
    <aura:if isTrue="{!v.isDiv}">
        Division of Two Numbers = {!v.total}
    </aura:if>
</aura:component>

Controller:
({
    Add : function(component, event, helper) {
        var a = component.get("v.num1");
        var b = component.get("v.num2");
        var total = parseInt(a) + parseInt(b);
        component.set("v.total",total);
        component.set("v.isAdd",true);
        component.set("v.isSub",false);
        component.set("v.isMul",false);
        component.set("v.isDiv",false);
    },
    
    Sub : function(component, event, helper) {
        var a = component.get("v.num1");
        var b = component.get("v.num2");
        var total = parseInt(a) - parseInt(b);
        component.set("v.total",total);
        component.set("v.isAdd",false);
        component.set("v.isSub",true);
        component.set("v.isMul",false);
        component.set("v.isDiv",false);
    },
    
    Mul : function(component, event, helper) {
        var a = component.get("v.num1");
        var b = component.get("v.num2");
        var total = parseInt(a) * parseInt(b);
        component.set("v.total",total);
        component.set("v.isAdd",false);
        component.set("v.isSub",false);
        component.set("v.isMul",true);
        component.set("v.isDiv",false);
    },
    
    Divi : function(component, event, helper) {
        var a = component.get("v.num1");
        var b = component.get("v.num2");
        var total = parseInt(a) / parseInt(b);
        component.set("v.total",total);
        component.set("v.isAdd",false);
        component.set("v.isSub",false);
        component.set("v.isMul",false);
        component.set("v.isDiv",true);
    },

    
    Clear : function(component, event, helper) {
        component.set("v.total",0);
        component.set("v.num1",0);
        component.set("v.num2",0);
        component.set("v.isAdd",false);
        component.set("v.isSub",false);
        component.set("v.isMul",false);
    }
})

Application:
<aura:application extends="force:slds">
    <c:Calculator/>
</aura:application>

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
Ajay K DubediAjay K Dubedi
Hi WonJeung,
Change your onClick - > onclick.  In your case the controller method was not fire.
Please try below code it works fine for me and let me know if this works for you. If still need modifications do let me know.

Component :
<aura:component >
    <aura:attribute name = 'num1' type = 'Integer' default = '15'></aura:attribute>
    <aura:attribute name = 'num2' type = 'Integer' default = '20'></aura:attribute>
    <aura:attribute name = 'sum' type = 'Integer'></aura:attribute>
    <div>
        <p>Add</p><lightning:button label = 'Add' onclick = '{!c.addMethod}'/>
        <p>{!v.num1} + {!v.num2} = {!v.sum}</p>
    </div>
</aura:component>



Controller :
 
({
    addMethod : function(component, event, helper) {     
        //Add numbers
        var num1 = component.get("v.num1");
        var num2 = component.get("v.num2");
        console.log(num1);
        console.log(num2);
        var sumResult = num1 + num2;
        component.set('v.sum', sumResult);
        
    }
})



I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi
This was selected as the best answer
WonJeungWonJeung
Thank you Ajay, you pointed out where it went wrong exactly! Everything worked out fine after I changed onClick to onclick.
Mithun S NaikMithun S Naik
Hai,

You can refer to this blog to build a calculator app in Aura.
https://viewonreview.com/salesforce-lightning-tutorial-for-beginners/
Aayush AmanAayush Aman
This is a simple Calculator using Helper to get the overview of working of Aura Components. 
Hope it helps! :)

Component
<aura:component implements="flexipage:availableForAllPageTypes" access="global" >
    
    <aura:attribute name="input1" type="integer" default=""/>
    <aura:attribute name="input2" type="integer" default=""/>
    <aura:attribute name="output" type="integer" default=""/>
    <aura:attribute name="showOutput" type="boolean" default="false"/>
 
    <div class="mainContainer">
        <h1 class="slds-text-heading_large">Calculator</h1>  <br/>
            <lightning:input label="Enter First Number" aura:Id="num1" value="{!v.input1}" placeholder="0" /><br/>
            <lightning:input label="Enter Second Number" aura:Id="num2" value="{!v.input2}" placeholder="0" /><br/>
        <div class="btnContainer">
            <lightning:button variant="brand" label="Add" onclick="{!c.addNum}" /> &nbsp; &nbsp; &nbsp;
            <lightning:button variant="brand" label="Subtract" onclick="{!c.subNum}"  /> &nbsp; &nbsp; &nbsp;
            <lightning:button variant="brand" label="Multiply" onclick="{!c.multNum}" /> &nbsp; &nbsp; &nbsp;
            <lightning:button variant="brand" label="Divide" onclick="{!c.divNum}"  /><br/>
        </div>
            <aura:if isTrue="{!v.showOutput}">
                    <span class="outputContainer"><b>Answer : {!v.output}</b>&nbsp; &nbsp; &nbsp;
                    <lightning:button  class="slds-button slds-button_text-destructive" label="Reset" onclick="{!c.resetForm}"  /></span>
            </aura:if>
    </div>
</aura:component>

_______________________________________________________________________________________________________________
Controller
 
({
    addNum : function(component, event, helper) {
        
        var res = helper.getValues(component, 'add');
        
        if(isNaN(res)){ //isnan(2)= false ->!false->true
            helper.errorHandler(component, 'error');
            return null;
        }   
        
        helper.setResults(component, res);
        
    },
    
    subNum : function(component, event, helper) {
        
        var res = helper.getValues(component, 'sub');
        
        if(isNaN(res)){ 
            helper.errorHandler(component, 'error');
            return null;
        }  
        
        helper.setResults(component, res);
        
    },
 
     multNum : function(component, event, helper) {
        
        var res = helper.getValues(component, 'multiply');
        
        if(isNaN(res)){
            helper.errorHandler(component,'error');
            return null;
        }  
        
        helper.setResults(component, res);
        
    },

    divNum : function(component, event, helper) {
        
        var res = helper.getValues(component, 'divide');
        
        if(parseInt(component.find('num2').get('v.value')) === 0){
            helper.errorHandler(component, 'error');
            return null;
        }
        
         if(isNaN(res)){
            helper.errorHandler(component);
            return null;
        }   
        
        helper.setResults(component, res); 
    },
    
    resetForm : function(component, event, helper){
        helper.errorHandler(component, 'reset');
    }
})


________________________________________________________________________________________________________________
Helper
 
({
    getValues : function(component, opt) {
        const nums= [];
        nums[0] = parseInt(component.find('num1').get('v.value'));
        nums[1] = parseInt(component.find('num2').get('v.value'));
        if(opt === 'add')
           return (nums[0]+nums[1]);
        if(opt === 'sub')
           return (nums[0]-nums[1]);
        if(opt === 'multiply')
           return (nums[0]*nums[1]);
        if(opt === 'divide')
           return (nums[0]/nums[1]);
    },
    
    setResults : function(component, res){
        component.set('v.output', res);
        component.set('v.showOutput', true);
    },
    
    errorHandler : function(component, task){
        if(task === 'error')
        alert('Enter the Valid number');
        component.set('v.input1','');
        component.set('v.input2','');
        component.set('v.showOutput', false);
    }
})
ASHISH KUMAR YADAV 7ASHISH KUMAR YADAV 7
Hi Ajay

I am facing error while implementing bmi in lwc.
code using html and javascript
========================
.html file
=======
<!DOCTYPE html>
<html lang="en">
<head>
    <title>BMI Calculator</title>
    <!--Google Font-->
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@500;700&display=swap" rel="stylesheet">
    <!--Stylesheet-->
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <div class="row">
            <input type="range" min="20" max="200" value="20" id="weight" oninput="calculate()">
            <span id="weight-val">20 kg</span>
        </div>
        <div class="row">
            <input type="range" min="100" max="250" value="100" id="height" oninput="calculate()">
            <span id="height-val">100 cm</span>
        </div>

        <p id="result">20.0</p>
        <p id="category">Normal weight</p>
    </div>

    <!--Script-->
    <script src="script.js"></script>
</body>
</html>

.js file
======
function calculate(){
    var bmi;
    var result = document.getElementById("result");

    var weight = parseInt(document.getElementById("weight").value);
    document.getElementById("weight-val").textContent = weight + " kg";

    var height = parseInt(document.getElementById("height").value);
    document.getElementById("height-val").textContent = height + " cm";

    bmi = (weight / Math.pow( (height/100), 2 )).toFixed(1);
    result.textContent = bmi;
    
    if(bmi < 18.5){
        category = "Underweight";
        result.style.color = "#ffc44d";
    }
    else if( bmi >= 18.5 && bmi <= 24.9 ){
        category = "Normal Weight";
        result.style.color = "#0be881";
    }
    else if( bmi >= 25 && bmi <= 29.9 ){
        category = "Overweight";
        result.style.color = "#ff884d";
    }
    else{
        category = "Obese";
        result.style.color = "#ff5e57";
    }
    document.getElementById("category").textContent = category;
}


converting above file in lwc
=======================

bmi.html
==========
<template>  
    <div class="slds-box slds-theme_shade">  
     <lightning-input type="number" name="height" id="height" label="Height" onchange={handleNumberoneChange} value={firstNumber}></lightning-input>  
     <lightning-input type="number" name="weight" id="weight" label="Weight" onchange={handleNumberTwoChange} value={secondNumber}></lightning-input>  
     <b>Body Mass Index [BMI] is : </b>  
      <!--<P>{resultValue}</p> -->
     <lightning-button label="Calculate" onclick={bmi}> </lightning-button>  
    </div>  
 </template>  

Bmi.js
======

import { LightningElement,track } from 'lwc';
export default class BmiLwc extends LightningElement {
    @track firstNumber;
    @track secondNumber;
    handleNumberoneChange(event) {
        this.firstNumber = parseInt(event.target.value);
    }
    handleNumberTwoChange(event) {
        this.secondNumber = parseInt(event.target.value);
    }
    handlecalculate(event){
        var bmi;
        var result = document.getElementById("result");
   
        var weight = parseInt(document.getElementById("weight").value);
        document.getElementById("weight-val").textContent = weight + " kg";
   
        var height = parseInt(document.getElementById("height").value);
        document.getElementById("height-val").textContent = height + " cm";
   
        bmi = (weight / Math.pow( (height/100), 2 )).toFixed(1);
        result.textContent = bmi;
       
        if(bmi < 18.5){
            category = "Underweight";
            result.style.color = "#ffc44d";
        }
        else if( bmi >= 18.5 && bmi <= 24.9 ){
            category = "Normal Weight";
            result.style.color = "#0be881";
        }
        else if( bmi >= 25 && bmi <= 29.9 ){
            category = "Overweight";
            result.style.color = "#ff884d";
        }
        else{
            category = "Obese";
            result.style.color = "#ff5e57";
        }
        document.getElementById("category").textContent = category;
    }
}