jQuery form validation function needs a NULL attribute

After successfully fixing one problem and making adjustments, I encountered a new issue with my form where the total sum wouldn't calculate unless all fields were filled out. Sometimes, I only have 2-4 entries that need to be factored into the quote. I am looking to modify the JavaScript to ensure it calculates any sum in the form, regardless of the number of products (1-10) entered in the current build.

Functional script

With NaN Error

jQuery(function($) {
  $(".qty, .tradeprice").change(function() {
    var total = 0;
    $(".qty").each(function() {
      var $qty = $(this),
        $row = $qty.closest('tr'),
        $tradePrice = $row.find('.tradeprice'),
        $subtotal = $row.find('.subtotal');
      subtotal = parseInt($qty.val(), 10) * parseFloat($tradePrice.val());
      total += subtotal;
      $subtotal.val(subtotal);
    });
    $('.total').val(total);
  }).change();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form action='insert.php' method='post'>
  <table width='60%' border='1' align='center' class='td'>
    <tr>
      <th width='26%' height='21' scope='col'>Customer ID</th>
      <td width='25%'><input type='text' name='CustomerID' id='CustomerID' /></td>
      <th height='24'>Revision</th>
      <td><input type='text' name='QuoteRevision' id='QuoteRevision' value="NEW" /></td>
    </tr>
    <tr>
      <th>Customer Name</th>
      <td><input type='text' name='CustomerName' id='CustomerName' /></td>
      <th height='24'>Customer Suburb</th>
      <td><input type='text' name='CustomerSuburb' id='CustomerSuburb' /></td>
    </tr>
    <tr>
      <th height='24'>Customer Address</th>
      <td><input type='text' name='CustomerAddress' id='CustomerAddress' /></td>
      <th height='24'>Customer Postcode</th>
      <td><input type='text' name='CustomerPostcode' id='CustomerPostcode' /></td>
    </tr>
    <tr>
      <th height='24'>&nbsp;</th>
      <td>&nbsp;</td>
      <th>&nbsp;</th>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <th height='24'>&nbsp;</th>
      <td>&nbsp;</td>
      <th>&nbsp;</th>
      <td>&nbsp;</td>
    </tr>
  </table>
  <p>&nbsp;</p>
  <table width='60%' border='1' align='center' class='td'>
    <tr>
      <th>F01U</th>
      <th>Model</th>
      <th>Description</th>
      <th>Trade Price</th>
      <th>Qty</th>
      <th>Total</th>
    </tr>
    (Input fields here, dynamically added)
  </table>
</form>

Answer №1

When it comes to NaN, it actually stands for "Not a Number." To ensure that you are dealing with numbers, consider using <input type="number> instead of sticking with the text format. Furthermore, always verify the success of parsing before incorporating any values.

subtotalAmount = parseInt($quantity.val(), 10) * parseFloat($price.val());
if(!subtotalAmount.isNaN()) // Add subtotal only if parsing is accurate
    finalTotal += subtotalAmount;

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

What is the method for retrieving the most recently added ID through AJAX calls?

Is there a way to retrieve the last inserted id with PHP in WordPress and use it on AJAX success to update a hidden field value? $wpdb->insert_id; ...

Implementing a user registration popup form with AJAX in Yii framework

I am currently utilizing the Yii-user extension for user registration, and it is working perfectly fine. However, my requirement is to display the registration form using ajax on pages that have a menu item for registration. I do not want the user to be re ...

What is the best way to delete a table that I created through my programming?

I have utilized the following code to create a table: <html> <head> <title>Table Time</title> </head> <body> <table border="1px"> <tr> ...

What steps can a web developer take to view user console errors?

Is there an effective method for a web developer to receive notifications of console errors logged by other authorized users? I am currently working with Express, Passport, and MongoDB. These errors may occur on either the client or server side. One approa ...

Updating multiple documents in Mongoose that have a specific element in an array

I have structured a Mongoose schema like this: const mongoose = require('mongoose'); const ItemSchema = mongoose.Schema({ id: { type: String, required: true, }, items: { type: Array, required: true, }, date: { type: ...

Prevent the elongation of HTML select elements in Bootstrap

Struggling to set the size of an HTML "select" field in Bootstrap 3 (latest) to normal width instead of 100%? Looking for a cleaner solution than resorting to tables or adding fields within bootstrap columns that might cause indentation issues due to borde ...

When utilizing the toISOString() function for conversion, the output received on Sat Apr 01 2023 00:00:00 GMT+0530 (India Standard Time) shows the date of the previous day

const today = new Date(); const lastMonthStart = new Date( today.getFullYear(), today.getMonth() - 1, 1 ); const lastMonthEnd = new Date( today.getFullYear(), today.getMonth(), 0 ); from = lastMonthStart.toISOString().split("T")[0]; t ...

Encountering an error message while trying to use `npm i`

I am attempting to set up the environment in order to run tests on JavaScript. I am using Windows 10 and Python 2.7. However, when I input the command 'npm -i', I receive an error message: https://i.stack.imgur.com/j2WXE.jpg To try and resolve ...

Challenges with Bootstrap input groups

Despite trying various solutions, nothing seems to be working for me. I attempted using width:200px, but the issue persists. Since my form was quite outdated, I decided to switch to a bootstrap version. However, while others are able to resolve the issue w ...

A step-by-step guide to identifying the clicked bar on a Chart.js graph

When using Chart JS to create a line bar chart, I am looking to specifically identify which bar was clicked on the chart and determine the index of that bar. This will allow me to display specific details for each clicked bar on a table. For example, click ...

What's the best way to identify the origin of a custom tag in a library?

I have a unique question that I need help with, so please bear with me. I recently started working on a new project at my job and it's built on some older technologies (Vue2, no ts support, etc.). It also relies on a few different UI libraries and de ...

What factors should you consider when selecting between Bootstrap and MDBootstrap for your class usage?

My CSS skills are not very advanced. I have been using MDBootstrap for most of the styling on my project, but I am not a fan of its table styling. I would prefer to use the table CSS class from regular Bootstrap instead of MDB. I have both dependencies inc ...

Activate DivMenu's second list item automatically

I've been trying to use the trigger function multiple times, but it just won't work. I need help with auto-triggering the menu of the second list element. Can someone please assist me? Here is a snippet of my code: $("document").ready(functio ...

Initiating a AJAX upload upon selection of a specific option from a select menu

Recently, I have been exploring ways to enhance my layout page by implementing an option for users to upload new logos on the spot. Currently, users are able to choose their desired image through a drop-down selection feature. I am interested in adding a f ...

jQuery failing to transmit JSON in AJAX POST call

I'm a bit perplexed at the moment, as I'm attempting to send data to my Node.js server using the code snippet below: $.ajax({type:'POST', url:'/map', data:'type=line&geometry='+str, succe ...

Struggling with the lack of two-way data binding functionality in Kendo UI

Recently, I encountered a challenge with my kendo-dropdownlist component. Initially, I was fetching data from an API using the kendo-datasource and everything was working smoothly. However, as I started to implement multiple instances of the kendo-dropdown ...

Ways to activate the JavaScript/AJAX script upon the dropdown value modification

I am currently working on a Django project where I want to execute a JavaScript/AJAX script when the value of a dropdown changes. Interestingly, the same code functions properly for a button but not for the dropdown. Below is the HTML code containing the ...

Utilizing Bootstrap for center-aligning a dropdown menu

I am using bootstrap to create a dropdown menu that I want to appear as a small box in the center of the page, similar to this example. Here is the HTML code I am working with: <div class="dropdown"> <button class="btn btn-default dropdown- ...

When using window.location.href and location.reload(), the updated page content from the server is not loaded properly

Currently, I am working on a form that is being updated via an AJAX call. Once the AJAX call successfully completes, I want to reload the page in order to display the new changes. Even though I tried using location.reload() and window.location.href after ...

Envelop the phrases onto a fresh line

I'm having trouble getting the text inside a div to display correctly. When the text is too long, it just keeps stretching instead of breaking into new lines. How can I make sure that the content displays as a block within the div? Thank you. .box ...