Let's build Stock Purchase Profit or Loss calculator with VanillaJs.

Let's go Folks , actually this project is one of the neog.camp level zero project. That I enjoy .

So here we go.

Html setup


<!DOCTYPE html>
<html lang="en">

<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">
    <link rel="stylesheet" href="style.css">
    <title>Stock : Profit and Loss Calculator</title>
</head>

<body class="card">
    <div class="container">
        <section class="container-heading">
            <h1>Check Profit or Loss on Your Stocks. </h1>
        </section>
        <form class="container-input">
            <label><input type="number" name="input" id="stock-purchase" placeholder="Enter Cost Price of Stock"
                    required> Purchase Price</label> <br>
            <label><input type="number" name="input" id="stock-quntity" placeholder="Enter Quantity of Stock" required>
                Stock Quantity</label> <br>
            <label><input type="number" name="input" id="stock-current" placeholder="Enter Current Price of Stock"
                    required> Current Price</label> <br>
            <button type="submit" class="btn-submit">Ckeck</button>
            <section class="container-msg" id="msg"></section>
        </form>
    </div>
    <script src="app.js"></script>
</body>
</html>

On index.html page we have create three input field for getting input value and also button and massage section for warnings or showing our profit or loss statements.

JavaScript

Create app.js file in your editor and also check you include/call it in index.html file. Remember that three input field we create in html . Now we have to access the input value with help of input fields. As I did in following snippet

var purPrice = document.getElementById("stock-purchase");
var quantity = document.getElementById("stock-quantity");
var curPrice = document.getElementById("stock-current");

For accessing input value, we have to use getElementById() to select html element by its Id. If given Id matches to input element Id then we can access that value. Also do same thing to access button and massage section.

Next we have to access form and to interact with form we have to create call back function .

const form = document.forms;

form.addEventListener("submit", function (e) {
        e.preventDefault();
});

Form in a html element so we can access it directly with help of document.forms .After that we add Event listener on form . when we click on submit button event listener activate and calls a default function where we gonna write our code . Here form tag is reload it self after submit. to prevent that we implement e.preventDefault() function where e is a parameter or event which is occurring.

In function write console.log("Button Click"); and open browser<Right click<Inspect Element<console. Click on Check button and see if massage is written in console then our event listener in working fine.

    let sellingPrice = Number(purPrice.value);
    let qnt = Number(quantity.value);
    let currentPrice = Number(curPrice.value);

we have to convert input values to number . So we use Number() function and pass input values in it to convert strings to number for further process.

if (sellingPrice > currentPrice) {
    // loss
} else {
   // profit
}

Let's create if else loop , so you can get either your having loss or profit. if your stock bought price is higher than current stock price then you are in loss else you are in profit.

let loss = ((sellingPrice - currentPrice) * qnt).toFixed(2);
let perLoss = (((sellingPrice - currentPrice) * 100) / sellingPrice).toFixed(2);

This is formula for loss and also loss in percentages and to get values in 0.00 format we use function tofixed() with value 2 to get double zeros after point.

Now do same for profit and implement both profit and loss logic in if else loop.

let loss = ((sellingPrice - currentPrice) * qnt).toFixed(2);
let perLoss = (((sellingPrice - currentPrice) * 100) / sellingPrice).toFixed(2);
console.log("loss : ", loss);
console.log("loss percentage :", perLoss);

Again use console.log() to console values that we get after calculation .

Now remove console.log .

let msg = document.getElementById("msg")

msg.innerHTML = `<div style="color: rgba(243, 13, 13, 0.76)">You lost ${perLoss}% loss. Your total loss is ${loss}.</div>`;

Now directly writing in html with help of innerHTML . to write in html with closure values we wrap massage with "\\massage" and give ${loss} ans ${perLoss} closures to access variables values.

Now do same with profit write in else loop.

if (sellingPrice > 0 && qnt > 0 && currentPrice > 0) {
//logic
}else{
msg.innerHTML = "Please enter values greater than Zero."
}

Also we have to check whether all input field values are not 0 or less than zero. for that we have to implement ifelse loop. it checks is values are greater than 0. If not then return a massage "Please enter values greater than Zero." and we are writing only text hence we wrap it in double quotations .

And Here we done. I like you to take care of css part. So this project can look even more attractive.

If you like this Project then please see my other projects on My Portfolio.

Thank You