Text content is not being displayed in JavaScript functions for forms

Currently, my code includes a form that captures 4 input quantities. When the user clicks the purchase button, the total counts of: total items, subtotal, sales tax, total, and final discount amount should be displayed based on the user's input.

The issue I'm facing is that nothing seems to print. Not even the error checking print statement. All that displays are "0" values for each value in the shopping cart.

I need help identifying where the problem lies. I suspect that the getElementsByClassId function might be causing the issue with the class inside the parentheses. I'm unsure where to begin troubleshooting.

<!doctype html>
<html lang="en>
<<head>
 <meta charset="utf-8">
<!-- Set the viewport so this responsive site displays correctly on mobile devices -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Page Title </title>
<!-- Include bootstrap CSS -->
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<!-- Include jQuery library -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
  thead { background-color: #333; color: #fff; font-weight: bold;  }
  .items, #nitems, #subtotal, #tax, #total, #final {text-align: right; width: 100px; }
  #checkout { margin-bottom: 45px; width: 200px; height: 50px; font-weight: bold; }
  #errors { padding-bottom: 200px; clear: both; font-weight: bold; clear: both; font-size: 20px;
  color: blue;
 }
</style>

</head>
<body class='container'>
<form name="testForm">
  <div class='row'>
  <div class='col-md-8'>
   <h2>Sam's Online Shop</h2>

   <h3>15% discount on all online sales </h3>

   <h3>Our World Famous Chocolates Now Available Online </h3>
     <table class='table'>
     <thead>
    ...

Answer №1

There seem to be several errors in your scripts, here is a list of the mistakes:

  • document.getElementById('Purchase').onclick // wrong id "Purchase" should be "checkout"
  • if (errors.length > 0) // missing closing brace { should be if (errors.length > 0){
  • displayitems(); // incorrect function "displayItems()" should be called
  • document.getElementsByClassId('form-control items'); // should use document.getElementsByClassName instead
  • (document.getElementById('ch-' + j + '-qnt').value) <0 ) // extra parenthesis ) after value, it should be (document.getElementById('ch-' + j + '-qnt').value < 0 )

document.getElementById('checkout').onclick = function() {

var milk = document.getElementById('ch-1-qnt').value;
var fine = document.getElementById('ch-2-qnt').value;
var both = document.getElementById('ch-3-qnt').value;
var truff = document.getElementById('ch-4-qnt').value;
// Checking for errors
var errors = checkErrors();
// Show the errors
if (errors.length > 0) {
    //displayErrors(errors);
    checkErrors();
}else {
    // Display total count of purchased items
    displayItems();
    // Calculate subtotal cost for all items
    var subTotal = Sub(milk, fine, both, truff);
    document.getElementById('subtotal').textContent = subTotal;
    // Calculate and show tax amount 
    var salesTax = Tax(subTotal);
    document.getElementById('tax').textContent = salesTax;
    // Calculate and show the total cost including subtotal and tax
    var Total = displayTotal(subTotal, salesTax);
    document.getElementById('total').textContent = Total;
    // Show discounted price
    var DiscountTotal = Total * .15;
    document.getElementById('final').textContent = DiscountTotal;
}

//Returns an array of error messages
function checkErrors() {
var list = [];

for (var j = 1; j<4; j++){

if (document.getElementById('ch-' + j + '-qnt').value <0 ) {
    document.getElementById('errors').innerHTML = list;
}   
}
return list;
}

// Showing total item counts
function displayItems() {
var total = 0;
var input = document.getElementsByClassName('form-control items');
for (var i=0; i<input.length; i++){
    total += parseFloat(input[i].value);
}
document.getElementById('nitems').textContent = total;  
}

// Function to calculate the subtotal for all 4 inputs
function Sub(milk, fine, both, truff) ...
......

};
......

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

Troubleshooting the issue with nodejs fs createWriteStream and file path prefixes

My goal is to call an API, iterate through an array of images, assign unique names to each image in the array, and then save them to a local directory. By simplifying the code, I can achieve this by writing them to the root folder. The sub folder was alrea ...

Bring in a sole getServerSideProps function to various pages in Nextjs

Is there a way to import the getServerSideProps method from this page to another and apply it across multiple pages? Here is the code snippet I am referring to: import DashboardLayout from "@app/layout/DashboardLayout"; import Overview from &quo ...

Hiding a div using swipe gestures in Angular

What am I trying to achieve? I aim to hide a div when swiped right. This specific action will close the pop-up that appears after clicking a button. What tools are at my disposal? I am utilizing Ionic framework for this task. Within my app.js, I have i ...

"Manipulating Arrays in JavaScript: Adding an Item at a Specific

I can easily insert into an array at a specific index when that index already exists. For example, if we have arr = [1, 2, 3, 4] and execute arr.splice(2, 0, 0), the result will be [1, 2, 0, 3, 4]. But what if I have an empty array that needs to be filled ...

Utilizing the closest method to retrieve the form element

As I review code written by another developer, I came across a surprising method used to retrieve a form object. HTML for Login Form <form id="frm_login" action=""> <input type="text" name="username" id="username"> <input type="passwor ...

Encountering an error when attempting to iterate over an undefined property using an API

I am trying to fetch all classes and their assignments from Google Classroom. I successfully used Google's example code for listing the classes, but had to write my own code for listing the assignments. While the code runs as expected and lists the as ...

What is the process for receiving updates while subscribing in ReactReduxContext.Consumer?

I am currently seeking a solution to staying updated on changes to a stored value in the Redux store by subscribing. I have attempted the following method: <ReactReduxContext.Consumer> {({store}) => { console.log('store:& ...

Does ECMAScript differentiate between uppercase and lowercase letters?

It has come to my attention that JavaScript (the programming language that adheres to the specification) is sensitive to case. For instance, variable names: let myVar = 1 let MyVar = 2 // distinct :) I have not found any evidence in the official specific ...

Is it possible to transmit a WebRTC frame to a Python script?

I recently built my first web app using Python and Django, which displays webcam frames of clients. 'use strict'; // For this project, I am only streaming video (video: true). const mediaStreamConstraints = { video: true, }; // Video element ...

Using the power of node.js to iterate through a loop of queries and execute

While I am running a for loop, within the loop itself I am executing a PostgreSQL query and storing the result in an array. However, I am unable to determine the order of execution. Here is my code: var array =[]; for(var i = 0 ; i< latitude.le ...

Cannot update VUEjs array following the splice operation

My array is only updating in the console and not in the DOM. I've already tried using :key but it's still not working. Here is my code: <div style="margin-top: 5px;" v-for="(file, index) in editedItem.file_name" ...

Making the toggle button functional on the navbar

Trying to customize my navbar for tablet and mobile devices is proving to be a challenge. I am looking for a way to make the dropdown button take up the entire page when clicked on. It seems like JavaScript might be the solution, but I'm not quite sur ...

Wait for another user keypress event in jQuery after a 0.5 second delay

Currently, I am working on developing a live search feature for my website. In order to reduce unnecessary requests and optimize performance, I am looking to implement a simple jQuery solution (while also ensuring that there is back-end flood control in pl ...

comparing jquery version 1 and jquery version 3 backward-compatible browsers

It has come to my attention that jquery 2.x does not offer support for legacy browsers. If I wish to accommodate those outdated Internet Explorer versions, I must resort to using jquery 1.x. However, I am curious about jquery 3.x. Does it provide support ...

The server attempted to send a request to the Open Api Vision API with the correct credentials, but unfortunately received an error indicating

I have recently set up a server to interact with OpenAI's vision API. Following their documentation, I integrated the code correctly on my server. However, every time I submit a request to the API, I encounter an issue. Despite having a Chat GPT Plus ...

Failed to load CSS and JS files

https://i.sstatic.net/tzp6n.png When attempting to launch my project on the server, I am facing issues with the CSS and JS files not loading properly. Below is the code snippet I have been using to include CSS/JS files: <script src="js/jquery.min.js" ...

Organize the array object by roles using mapping and grouping techniques

Given an object array with roles as keys and values, I want to group them according to the roles assigned. Here is the sample data: { users: [ { firstName: 'Will', lastName: 'Jacob', email: '<a href="/cd ...

The Ink CLI is anticipating the component to be a function

Currently delving into the world of the Ink library for constructing a console application in Javascript. Despite having experience with React, this is a different ball game. Some of the nuances are proving to be quite perplexing. I've managed to get ...

Identify a request in NodeJS without relying on express or accessing the request object independently of an express middleware

I am struggling with accessing the request object outside of an express middleware in NodeJS. In my code snippet below, I need to read the request object from a file called mongoose_models.js, where I don't have access to the express middleware argume ...

Is there a way to preserve line breaks when programmatically copying text to the clipboard with JavaScript?

Utilizing Javascript alongside a duo of devexpress asp.net controls to dynamically duplicate the contents of an ASPxMemo (multiline textfield) and assign those contents as the body of an email. The copying and pasting is functioning correctly for the most ...