Receiving an unknown value from the input field

I can't seem to retrieve the value of my input, as quantityElement.Value consistently returns undefined.
Here is the section of my HTML and JS that I am struggling with. In my JavaScript function, the quantityElement always gives me an undefined when trying to access the input's value.

This is my HTML:

<section class="container content-section">
    <h2 class="section-header">CART</h2>

    <div class="cart-items">

        <div class="cart-row">
            <span class="cart-item cart-header cart-column">ITEM</span>
            <span class="cart-price cart-header cart-column">PRICE</span>
            <span class="cart-quantity cart-header cart-column">QUANTITY</span>
        </div>

        <div class="cart-row">

            <div class="cart-item cart-column">

                <img class="cart-item-img" src="Images/product-1.jpg" width="100" height="100">
                <span class="cart-item-title">T-Shirt</span>

            </div>

            <span class="cart-price cart-column">$19.99</span>

            <div class="cart-quantity cart-column">
                <input class="cart-quantity-input" type="number" value="1">
                <button class="btn btn-danger" type="button">REMOVE</button>
            </div>
        </div>

        <div class="cart-row">

            <div class="cart-item cart-column">

                <img class="cart-item-img" src="Images/product-3.jpg" width="100" height="100">
                <span class="cart-item-title">PANTS</span>

            </div>

            <span class="cart-price cart-column">$19.99</span>

            <div class="cart-quantity cart-column">
                <input class="cart-quantity-input" type="number" value="2">
                <button class="btn btn-danger" type="button">REMOVE</button>
            </div>


        </div>
    </div>

    <div class="cart-total">
        <span class="cart-total-title">Total</span>
        <span class="cart-total-price">$39.98</span>
    </div>

    <button class="btn btn-primary btn-purchase" type="button">PURCHASE</button>

</section>

Javascript:

function updateCartTotal() {
  var cartItemContainer = document.getElementsByClassName("cart-items")[0];
  var cartRows = cartItemContainer.getElementsByClassName("cart-row");
  var total = 0;
  for (var i = 0; i < cartRows.length; i++) {
    var cartRow = cartRows[i];
    var priceElement = cartRow.getElementsByClassName("cart-price")[0];
    var quantityElement = cartRow.getElementsByClassName(
      "cart-quantity-input"
    )[0];
    var price = parseFloat(priceElement.innerText.replace("$", ""));
    var quantity = parseFloat(quantityElement.value);

    total = total + price * quantity;
  }
  document.getElementsByClassName("cart-total-price")[0].innerText = total;
}

Answer №1

Initially, I eliminated the 'cart-price' CSS class from this particular element:

<span class=" cart-header cart-column">PRICE</span>

and included an 'onclick' attribute to the button

<button onclick="updateCartTotal()" class="btn btn-primary btn-purchase" type="button">PURCHASE</button>

Subsequently, I made alterations in the JavaScript code, such as:

function updateCartTotal() {
  var cartItemContainer = document.getElementsByClassName("cart-items")[0];
  var cartRows = cartItemContainer.getElementsByClassName("cart-row");
  var total = 0;

  for (var i = 0; i < cartRows.length; i++) {
    var cartRow = cartRows[i];
    var priceElement = document.getElementsByClassName("cart-price")[0];
    var quantityElement = document.getElementsByClassName("cart-quantity-input")[0];
    var price = parseFloat(priceElement.innerText.replace("$", ""));
    var quantity = parseFloat(quantityElement.value);

    total = total + price * quantity;
  }
  document.getElementsByClassName("cart-total-price")[0].innerText = total;
}

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

Automated Facebook Wall Publishing

I have successfully integrated a feature in my application where users can post status updates, photos, and URLs on their Facebook Like stream. I have also added an option for users to post directly on Facebook by including a checkbox. When the user clicks ...

Preserving Scroll Location Through Back Button Usage and Ajax Manipulation of the Document Object Model

Currently, I am incorporating a feature where results are loaded in using ajax with an infinite scroll. However, there is an issue when a user clicks on an item in the list and navigates away from the page - upon returning by clicking the back button, they ...

issues with jquery functionality on mobile devices

I'm currently working on a website where I've implemented a jQuery script to dynamically load specific parts of an HTML page with an ID of 'guts' into the main content area. The goal was to keep the menu consistent while only changing t ...

Changing dimensions of cube on stable base

I'm currently working on a project involving a dynamic cube that can be scaled in real time by adjusting its mesh. However, I'm facing a challenge in keeping the cube fixed to the floor while changing its height. Here's a snippet of the code ...

ng-class expressions are constantly evolving and adapting

Within a div, I am utilizing ng-class="{minifyClass: minifyCheck}". In the controller, I monitor changes in two parameters - $window.outerHeight and $('#eventModal > .modal-dialog').height(). If there are any changes, I trigger the minifyChan ...

What is the best way to send requests to a GraphQL server within my Redux action?

I am looking to transition my React+Redux application from using rest-requests to graphql-requests in my actions. What is the easiest way to accomplish this change seamlessly? I have come across Apollo while researching, but I prefer a simpler method to i ...

Error always occurs during validation when sending files through AJAX in Laravel

Currently, I am working on a form where I am attempting to send a file (PDF, DOC, DOCX) to my controller. Here is the structure of my form: <div class="modal-body"> {{-- alert if any error exist --}} <div ...

NextJS struggles to load EditorJS plugins

I am currently working on integrating EditorJS into my NextJS project. The editor is loading properly without any plugins, with only paragraph as a block option. However, I'm facing an issue when trying to add plugins using the tools prop which result ...

jQuery file uploader only transmitting a single chunk

Currently, I am integrating the jQuery file uploader into my Django application. I am encountering an issue where Django is only receiving one chunk of my large file. Initially, I suspected a problem with my UploadFileHandler; however, upon logging the ch ...

Use application/json for the PUT request body instead of plain/text format

Currently, I am experimenting with React and attempting to send a PUT request to an API. Despite my efforts to set the body as content-type application/json, it continues to be sent as text/plain. Whenever I include the header "Content-Type" : "application ...

The statusMessage variable is not defined within the "res" object in a Node Express application

I am currently developing a Node.js & Express.js application and I am in need of creating a route to display the app's status. router.get('/status', function(req, res) { res.send("Current status: " + res.statusCode + " : " + res.stat ...

Is there a way to display the items I've added to my cart when I click on it?

I have a collection of product IDs stored in local storage. I am using these IDs to populate the list of products added to the basket. Strangely, when I navigate to the basket page, the products do not appear unless I make a small code modification or re-s ...

Utilizing a range input (slider) to extract data of importance

When dynamically adding a slider to a page using a specific string, like the one shown below: "<input type=\"range\" name=\"aName\" min=\"1\" max=\"9\"/>"; After appending it to the page with pure JavaScript, ...

The variable from AJAX is not being displayed in PHP

Need help with transferring a JavaScript variable to the same PHP page. The following code is what I have so far: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script& ...

The UTF-8 data sent by JQuery AJAX is not being correctly processed by my server, but only in Internet Explorer

When I send UTF-8 Japanese text to my server, it works fine in Firefox. Here are the details from my access.log and headers: /ajax/?q=%E6%BC%A2%E5%AD%97 Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7 Content-Type application/x-www-form-urlencoded; char ...

What is the process for importing a jquery plugin like turnjs into a React component?

After searching through countless posts on stackoverflow, it seems like there is no solution to my problem yet. So... I would like to integrate the following: into my react COMPONENT. -I attempted using the script tag in the html file, but react does no ...

What could be causing this code to malfunction on jsfiddle?

Why doesn't this code from W3schools work on jsfiddle? I tried to implement it here: https://jsfiddle.net/u6qdfw5f/ <!DOCTYPE html> <html> <title>W3.CSS</title> <meta name="viewport" content="width=device-width, initial ...

If checkboxes are found within the table's rows and cells, add the parent row class if none of the

I am attempting to implement a small script within my table under the following conditions: The table contains a checkbox within each tr td, and I want my jQuery script to be applied only if the selector identifies a tr where all td checkboxes are unchecke ...

A guide on converting a Javascript datetime to a C# DateTime parameter

In a previous question that I asked on StackOverflow, I mentioned that I was able to retrieve my values successfully as the object was no longer null. The object contains a DateTime property named CreatedOn, which I am sending from JavaScript using new Dat ...

Discovering the present width of an Angular element after it has been eliminated

Imagine you have a horizontal navigation bar coded as follows: HTML: <ul> <li ng-repeat="navItem in totalNavItems">{{name}}</li> </ul> CSS: ul, li { display: inline-block; } The data for the navigation items is fetched from thi ...