Increase or decrease the input value by clicking on a button

Having an issue where the quantity value properly increases and decreases when clicking on the + or - button, but I also want the price to increment and decrement accordingly. I need to be able to adjust the price when clicking on the increase or decrease buttons.

https://i.sstatic.net/o6SgI.png

index.html

This is my index.html file where all of the UI elements are located.

 <div class="container">
        <h3>Solar terrace light with inbuilt panel</h3>
        <div class="row">
            <div class="col-md-6">
                <img src="https://s3.ap-south-1.amazonaws.com/rzp-prod-merchant-assets/payment-link/description/pr11_hq0cy7e5cmwbzw"
                    class="w-75">
            </div>
            <div class="col-md-6 mt-3">
                <div class="card p-4">
                    <h4>Payment Details</h4>
                    <div class="row mt-2">
                        <div class="col-3">
                            <p>Qty.</p>
                        </div>
                        <div class="col-9">
                            <div class="quantity">
                                <button class="btn minus-btn disabled" type="button">-</button>
                                <input type="text" id="quantity" value="1">
                                <button class="btn plus-btn" type="button">+</button>
                            </div>

                            <!--will calculate price---->

                        </div>
                    </div>
                    <div class="row mt-2">
                        <div class="col-3">
                            <p>Name</p>

                        </div>
                        <div class="col-9">
                            <input type="text" class="w-100">

                        </div>
                    </div>
                    <div class="row">
                        <div class="col-3">
                            <p>Email</p>

                        </div>
                        <div class="col-9">
                            <input type="text" class="w-100">

                        </div>
                    </div>
                    <div class="row">
                        <div class="col-3">
                            <p>Phone</p>

                        </div>
                        <div class="col-9">
                            <input type="text" class="w-100">

                        </div>
                    </div>
                    <div class="row">
                        <div class="col-3">
                            <p>Price</p>

                        </div>
                        <div class="col-9">
                            <p class="total-price">
                                <span><i class="fas fa-rupee-sign" style="color: black;"></i></span>
                                <input id="price" class="text-dark" value="12,999"> 
                            </p>
                        </div>
                    </div>
                    <button class="btn btn-primary">Buy Now</button>
                </div>
            </div>
        </div>
    </div>

index.js

This is my index.js file where all the logic for incrementing and decrementing is implemented.

  document.querySelector(".minus-btn").setAttribute("disabled", "disabled");

        //taking value to increment decrement input value
        var valueCount

        //taking price value in variable
        var price = document.getElementById("price").innerText;

        //price calculation function
        function priceTotal() {
            var total = valueCount * price;
            document.getElementById("price").innerText = total
        }

        //plus button
        document.querySelector(".plus-btn").addEventListener("click", function () {
            //getting value of input
            valueCount = document.getElementById("quantity").value;

            //input value increment by 1
            valueCount++;

            //setting increment input value
            document.getElementById("quantity").value = valueCount;

            if (valueCount > 1) {
                document.querySelector(".minus-btn").removeAttribute("disabled");
                document.querySelector(".minus-btn").classList.remove("disabled")
            }

            //calling price function
            priceTotal()
        })

        //plus button
        document.querySelector(".minus-btn").addEventListener("click", function () {
            //getting value of input
            valueCount = document.getElementById("quantity").value;

            //input value increment by 1
            valueCount--;

            //setting increment input value
            document.getElementById("quantity").value = valueCount

            if (valueCount == 1) {
                document.querySelector(".minus-btn").setAttribute("disabled", "disabled")
            }

            //calling price function
            priceTotal()
        })

Answer №1

There are several issues with your code: Firstly, input values are treated as strings by default, so you won't be able to perform arithmetic operations on them without converting them using parseInt (for integers) or parseFloat (for decimals). Secondly, if you want to retrieve text from an input element, use ".value" instead of ".innerText". Lastly, when displaying a product price like 12999, ensure it is in its full numerical format and only show commas or periods based on the desired representation.

On the HTML side, your code should resemble this:

<div class="container">
        <h3>Solar terrace light with inbuilt panel</h3>
        <div class="row">
            <div class="col-md-6">
                <img src="https://s3.ap-south-1.amazonaws.com/rzp-prod-merchant-assets/payment-link/description/pr11_hq0cy7e5cmwbzw"
                    class="w-75">
            </div>
            <div class="col-md-6 mt-3">
                <div class="card p-4">
                    <h4>Payment Details</h4>
                    <div class="row mt-2">
                        <div class="col-3">
                            <p>Qty.</p>
                        </div>
                        <div class="col-9">
                            <div class="quantity">
                                <button class="btn minus-btn disabled" type="button">-</button>
                                <input type="text" id="quantity" value="1">
                                <button class="btn plus-btn" type="button">+</button>
                            </div>

                            <!--will calculate price---->

                        </div>
                    </div>
                    <div class="row mt-2">
                        <div class="col-3">
                            <p>Name</p>

                        </div>
                        <div class="col-9">
                            <input type="text" class="w-100">

                        </div>
                    </div>
                    <div class="row">
                        <div class="col-3">
                            <p>Email</p>

                        </div>
                        <div class="col-9">
                            <input type="text" class="w-100">

                        </div>
                    </div>
                    <div class="row">
                        <div class="col-3">
                            <p>Phone</p>

                        </div>
                        <div class="col-9">
                            <input type="text" class="w-100">

                        </div>
                    </div>
                    <div class="row">
                        <div class="col-3">
                            <p>Price</p>

                        </div>
                        <div class="col-9">
                            <p class="total-price">
                                <span><i class="fas fa-rupee-sign" style="color: black;"></i></span>
                                <input id="price" class="text-dark" value="12.999"> 
                            </p>
                        </div>
                    </div>
                    <button class="btn btn-primary">Buy Now</button>
                </div>
            </div>
        </div>
    </div>

And for the JavaScript part:

document.querySelector(".minus-btn").setAttribute("disabled", "disabled");

        //variable for value count incrementing/decrementing
        var valueCount

        //setting price value in a variable
        var price = document.getElementById("price").value;
        console.log(price);

        //function for calculating total price
        function priceTotal() {
            var total = parseFloat(valueCount) * parseFloat(price);
            document.getElementById("price").value = total
        }

        //plus button functionality
        document.querySelector(".plus-btn").addEventListener("click", function () {
            //getting input value
            valueCount = document.getElementById("quantity").value;

            //increasing input value by 1
            valueCount++;

            //setting incremented input value
            document.getElementById("quantity").value = valueCount;

            if (valueCount > 1) {
                document.querySelector(".minus-btn").removeAttribute("disabled");
                document.querySelector(".minus-btn").classList.remove("disabled")
            }

            //calling price function
            priceTotal()
        })

        //minus button functionality
        document.querySelector(".minus-btn").addEventListener("click", function () {
            //getting input value
            valueCount = document.getElementById("quantity").value;

            //decreasing input value by 1
            valueCount--;

            //setting decremented input value
            document.getElementById("quantity").value = valueCount

            if (valueCount == 1) {
                document.querySelector(".minus-btn").setAttribute("disabled", "disabled")
            }

            //calling price function
            priceTotal()
        })

Answer №2

To update the content using "innerHTML", replace it with "value" and eliminate the "," (comma) from the price. It's as simple as that!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to transfer the variable name between different node modules for the purpose of using it as a chat room identifier in a socket.io application

Users are able to provide a room name, however when using module.exports in a separate file to retrieve it, the value shows as undefined. This issue likely arises from the asynchronous nature of the process. //roomcheck.js var nsp = io.of("/gameroom"); n ...

Implementing route prefix in a combination of express and react deployment

I'm currently facing a challenge while trying to deploy a react app that utilizes router functionality with express. The react app is expected to be accessible via the /dashboard route. At first glance, everything seems to be working smoothly on the ...

Guide on storing images in a designated folder using CodeIgniter

My code is located in view/admin_view2.php <?php echo form_open_multipart('home_admin/createBerita'); ?> <div class="form-group" > <label class="control-label">upload foto</label> <inpu ...

When using jQuery to select elements of a specific class, make sure to exclude the element that triggered the

A dynamic number of divs are generated from a data source. Each div contains an image button and another div with text. While the actual scenario is more complex, we can present a simplified version: <div id="main"> <div id="content_block_1" ...

Inserting a new row into a particular table

I am working on a project where I have a table that displays different exercises. My goal is to allow users to add a new row for each exercise individually. Currently, the snippet below shows how I have implemented this: <!DOC ...

Is it possible to simultaneously run watchify and node-sass watch together?

Currently, I am utilizing npm scripts in conjunction with watchify and node-sass while incorporating the -w parameter. I am curious if it is feasible to execute both of these 'watch' commands simultaneously. Would this setup ensure that only sty ...

What methods can I use to insert an array of objects into a Query?

I'm currently trying to understand how I can pass an array of objects into my GraphQL query. The documentation seems a bit confusing on this matter. In my project, I am using Apollo on the frontend, Graphql-yoga on the backend, and Prisma as my databa ...

Having trouble with the "setValue" property being undefined error. Looking for a solution to input text into a codeMirror element using Selenium WebDriver with Java

Currently, I am attempting to input text into a textarea field that is recognized as CodeMirror. Below is the code snippet I have been working with: {... WebElement scriptField = this.getDriver().findElement(By.cssSelector(".CodeMirror-line>span")); ...

Convert Excel Spreadsheet data into an interactive HTML chart in real time

Looking for a solution to update an Excel spreadsheet monthly and display it on a Blackberry browser? I've already built a website with all the spreadsheet information using HTML lists and CSS for charts. I need help loading a new spreadsheet into th ...

Switching between all tabs simultaneously in an MDX page (React + Gatsby + MDX) using @reach/tabs

Creating a Tab component for a Gatsby site has proved to be a bit tricky. Imagine having a page with multiple tabs all labeled the same: Heading 1 First tab block Tab 1 | Tab 2 Content Tab 1 Second tab block Tab 1 | Tab 2 Content Tab 1 for the second bl ...

The user authentication is not recognized in the current session (Node.js, Express, Passport)

I have encountered an issue where req.user is undefined, despite my efforts to troubleshoot for over 4 hours. I even resorted to copying and pasting the server/index.js file from a friend's server, modifying the auth strategy to suit my own, but the p ...

AngularJS: Advanced Routing for Dynamic Web Applications

Hello, I am currently exploring the possibility of implementing something similar to this code snippet using AngularJS: $routeProvider .when('/root/:controllerName/blah/:blahId/blah/:blah', { templateUrl: '/tmpl/:controllerName ...

Generating a JSON file by combining data from two separate lists in order to render a visually appealing stacked bar chart

Combining two lists to create a JSON for generating a stacked bar chart using JavaScript list1 = ['2019-03-05', '2019-02-20', '2019-02-20', '2019-02-19', '2019-02-18', '2019-02-16', '2019-02 ...

Once the Ajax request is finished, the cookie deletion function ceases to function

When the website loads, a cookie is generated using PHP before any other content or headers are sent. This is done with the following code: $steam_login_verify = SteamSignIn::validate(); if(isset($_COOKIE['userid'])) { //work with cookie va ...

How to delete the final character from a file stream using node.js and the fs module

My current project involves using node.js to create an array of objects and save them to a file, utilizing the fs library. Initially, I set up the write stream with var file = fs.createWriteStream('arrayOfObjects.json'); and wrote an opening brac ...

Keep elements in position when their bottom edge becomes visible while scrolling

This task may appear intricate, but I will do my best to explain it! I want to create a continuous scrolling article display similar to Bloomberg Politics (), but with a slight twist. My idea is to have the current article's bottom edge stick to the ...

Problem with exporting default class in Babel/Jest conflict

Currently, I am facing a challenge while testing the code using jest. The issue seems to be related to babel, especially regarding the export of a default class. Here is an example of the code causing the problem... export default class Test { get() { ...

Comparison of Transform plugin and Syntax plugin within Babel

I am interested in incorporating Class properties into my webpack configuration. While following a tutorial on the website (www.survivejs.com), I came across two plugins being added to the .babelrc file: babel-plugin-syntax-class-properties and babel-plugi ...

Navigating Google Oauth - Optimal User Sign in Locations on Frontend and Backend Platforms

What are the distinctions between utilizing Google OAuth versus implementing user sign-ins at the frontend of an application, as opposed to handling them on the backend? For instance, managing user authentication in React to obtain the ID and auth object ...

retrieve the state property from NavLink

I am encountering an issue with passing objects through components in my project. Specifically, I have a chat object within a component that defines a NavLink. When a user clicks on the ChatsElement, which is a link, the page navigates to the URL /friends/ ...