Performing calculations in Javascript using input and span elements

<input type="number" name="quantity" id="quantity">
<span id="price">4000</span>

<input type="text" value="" id="total" readonly>
<input type="button" value="calculate Total Price" onClick="calculate()">

I have a form with fields for quantity and price, and I want to calculate the total price using a JavaScript function when the user clicks the calculate button. However, the result is currently coming out as NaN. Here is the JavaScript function I am using:

function calculateTotalPrice() {
        var quantity = document.getElementsByName('quantity').value;
        var price = document.getElementById('price');
        var parsedPrice = parseInt(price);
        var total = quantity * parsedPrice;
        document.getElementById("total").value = total;
}

Answer №1

When encountering a method in plural form, like getElementsByName, it retrieves multiple elements known as a nodeList. Even when there is only one matching element, you still receive a nodeList. A nodeList does not hold a value, but you can access it like an array and retrieve the first element in the list as shown below:

var quan = document.getElementsByName('quantity')[0].value;

Similarly, getElementById brings back an element, not a number. To access the innerHTML, you can use the following:

var pri = document.getElementById('price').innerHTML;

It is important to always specify the radix when using parseInt, like so:

parseInt(pri, 10)

It's worth noting that in most cases, you don't need to parse it when performing multiplication.

FIDDLE

Answer №2

To achieve this task, you can utilize a for loop to iterate through each individual value and store it in a variable. Here is an example of how you can accomplish this:

for(i=0; i<quan.length; i++) {
  var sum+= quan[i];
}

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

Utilizing ES6 JavaScript for Creating Static Methods and Angular 2 Services

During the development of an Angular 2 app involving multiple calculation services, I encountered some interesting questions: Is it beneficial to use static in an Angular service provided on the application level? Or is it unnecessary? How does a static ...

Switch to a different element by rolling over one

I need assistance with a menu setup where the submenus are located in separate divs on the page. Both the parent elements and submenus have numerical identifying IDs, and I am struggling to create a rollover effect that would automatically open the corresp ...

Passing the contents of a datatable as parameters to a PHP script

I am facing a challenge with my datatable that has two columns, "Name" and "Age". After populating the datatable using Ajax, I create a button for each row. The goal is to send the "Name" and "Age" fields of the clicked row to a PHP script, which will then ...

Can you tell me the alternative for window.location.href when using Vue router?

After performing an action in my Vue app, I am looking to redirect to a different page within my single-page application (SPA). However, when I use the code window.location.href = "/subpage", the page refreshes and I end up losing cached data tha ...

"Enjoying a table header that scrolls freely with autoscroll feature

Resolved - http://jsfiddle.net/CrSpu/11704/ I'm facing an issue with a table that has autoscroll functionality. I am looking to freeze the header of the table when automatic scrolling occurs, or you can test it out using my code pen. I'm uncer ...

arranging data in various categories with React.js

Can anyone figure out why this code is struggling to properly sort based on columns? sort(key){ this.setState({ [`toggle-${key}`]: !this.state[`toggle-${key}`], data: sortBy(this.state.data, [key], this.state[`toggle-${key}`]).map(v => ...

Issues with creating modal images using only JavaScript

I am facing an issue with modal popup images. I have a collection of images and attempted to implement this code (with some modifications): https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_modal_img However, it seems to only work for the initi ...

Updating is not happening with ng-repeat trackBy in the case of one-time binding

In an attempt to reduce the number of watchers in my AngularJS application, I am using both "track by" in ngRepeat and one-time bindings. For instance: Here is an example of my view: <div ng-repeat="item in items track by trackingId(item)"> {{ : ...

Displaying a blank column in a table using JavaScript

I am trying to write a JavaScript function that will add a new column to a table. I want this new column to be displayed at the index where it is added, and then hidden once the addition is complete. Here is the code for my method: function addColumnToTa ...

When any part of the page is clicked, the data on the Angular page will automatically

Clicking the mouse anywhere on the page, even in a blank spot, causes the data array to resort itself. I understand that clicking may trigger a view change if an impure pipe is set, but I have not used one. So I am puzzled because my development testing ...

Preventing autocomplete from filling in empty password fields (React.js)

Once the browser autocompletes my login form, I notice that the password input's value is initially empty. However, when I click on the password field, suddenly the value appears. Additionally, there are several inexplicable events being triggered by ...

Ways to extract data from a chosen radio button choice

Excuse me, I have a form with an input field and radio buttons. Can someone please help me with how to retrieve the value of the selected radio button and then populate that value into the input text field? For reference, here is the link to the jsfiddle: ...

Sending Python Object from Django View to Javascript Script in Template

Here is a basic code snippet created solely to illustrate a problem. While the task at hand can be achieved without JavaScript, I am exploring how to accomplish it using JavaScript for my actual code where it is necessary. In view.py Inside the play_game ...

Clicking the responsive menu does not reveal the hidden overlay div as expected

Struggling with finding the correct function to open the hidden div of my responsive menu on my new website. Check out my code: https://codepen.io/anon/pen/XRJRGE <a class="page-head__menu" id="js-menu" href="#" onClick="open()">Menu< ...

Steps for releasing a third-party library that is compatible with both Angular 2 and Angular 4

Currently, I am utilizing a third-party library for Angular that is compatible with Angular 2. However, I want to make sure this library can support all versions of Angular, including Angular 4 and Angular 5. How can I go about publishing an updated vers ...

XPages component retrieval function is malfunctioning

Utilizing an XPage with JQuery dialog and client-side validation adds efficiency to the user input process. However, there seems to be a disconnect between the client-side validation and server-side properties. Although the client-side validation functions ...

Using AJAX/JQuery along with PHP to instantly send notifications without refreshing the page for a contact form

Website URL: This website was created by following two separate tutorials, one for PHP and the other for AJAX. The main objective was to develop a contact form that validates input fields for errors. If no errors are found, a success message is displayed ...

CSS: Unexpected value, received NaNrgb

I was attempting to incorporate a checkbox into a Bootstrap form that turns green when it is checked. Here is the code I used: function updateColor() { $("#check1").animate({ "background-color": "rgb(209, 231, 221)" }); } <script src="http ...

I'm receiving /generate_seeker/?complete_list=true, but what I actually need is /generate_seeker?complete_list=true

Check out this code snippet that utilizes axios in a React project. axios.get(`https://resolab-backend.herokuapp.com/core/create_seeker`,{ params:{ complete_list : true }, headers:{ 'Authorization': `Token ${cookies.get("token")}` } ...

testing express router with several different handlers

I have been testing my guard middleware and everything appears to be functioning correctly, but my expect statement is failing. /// auth.test.js const request = require('supertest'); const express = require('express'); const app = req ...