I'm wondering if there is a method for me to get only the count of input fields that have the class "Calctime" and are not empty when this function is executed

Currently, I am developing an airport application that aims to track the time it takes to travel between different airports. In this context, moving from one airport to another is referred to as a Sector, and the duration of time taken for this journey is known as Block Time.

In my form design, there are provisions for users to input details for up to 8 Sectors. However, I face a challenge with displaying the total number of only filled out sectors before hitting the submit button. This can be achieved by having the field labeled # of Sectors show the count of completed sectors by identifying how many fields marked with the 'Calctime' class are not empty. Notably, all fields designated as Block Time have the 'Calctime' class associated with them.

To provide further insight, you can view the form layout featuring 8 Sectors.

The function I have created to address this issue seems to be returning the total number of fields (8) instead of just the count of filled-up fields. The function script in question:

function sectors(){
 var items = [...document.querySelectorAll('.calctime')]; //demo to count number of empty
 document.getElementById('sector').value = items.length
 }

Answer №1

You can loop through the form fields to verify their contents.

function checkFields(){
 var elements = [...document.querySelectorAll('.calctime')]; //example to calculate number of empty fields
 let filledCount=0;
 elements.forEach(element => {
     if(element.value) filledCount++;
 })
 document.getElementById('sector').value = filledCount;
}

Answer №2

To ensure all input fields are filled, adding a placeholder (even a blank one) is recommended. Utilize

querySelectorAll('element:not(:placeholder-shown))
to target unfilled inputs effectively.

Including a placeholder is not only beneficial for usability but also essential for accessibility purposes.

// function to count filled inputs
function countFilledInputs() {
  let filled_inputs = document.querySelectorAll('input.calctime:not(:placeholder-shown)');
  console.log(filled_inputs.length);
}


// eventListeners for demo purposes
window.addEventListener('DOMContentLoaded', countFilledInputs);
const INPUTS = document.querySelectorAll('input.calctime');
INPUTS.forEach(input => input.addEventListener('change', countFilledInputs));
<input class="calctime" placeholder="">
<input class="calctime" placeholder="">

Answer №3

if you are looking to filter a list based on values present, you can utilize the array.property.filter method. Below is an example:

 button.addEventListener('click',()=>{
   let items = [...document.querySelectorAll('.calctime')];  
   const button = document.getElementById('button')
   items = items.filter((item) => !!item.value )

   document.getElementById('sector').value = items.length
 })
<div>
  <input type="text" class="calctime" />
  <input type="text" class="calctime" />
  <input type="text" class="calctime" />
  <input type="text" class="calctime" />
  <input type="text" class="calctime" />
  <input type="text" class="calctime" />
  <input type="text" class="calctime" />
  <input type="text" class="calctime" />
</div>
<div>
  <input type="text" id="sector" readonly />
  <button id="button">button</button>
</div>

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

Is there a way to retrieve the size of a three.js group element?

Obtaining the dimensions of a mesh (Three.Mesh) can be done using the following code: mymesh.geometry.computeBoundingBox() var bbox = mymesh.geometry.boundingBox; var bboxWidth = bbox.max.x - bbox.min.x; var bboxHeight = bbox.max.y - bbox.min.y; var bbo ...

"Enhancing security measures with multiple nonce for Content Security Policy

I am encountering an issue with my single page application, which is developed in .net core MVC 2.2. The application loads html sections on the fly. In the main document, I have added a Content Security Policy (CSP) policy with a dynamically generated hea ...

Tips for automatically expanding all nodes with children when the page loads in the Wix Angular tree control

Is there a way to automatically expand all nodes with children when the page loads in an Angular tree control? The tree control is full of useful features, but this specific functionality seems to be missing. It does have a property for expanded nodes. Do ...

What is the best way to create an image in the shape of a perfect circle?

Incorporating the Bootstrap V5.0 framework into my project, I set out to create a div containing a circular image along with some text content. While I was able to use a 50% radius to achieve a circular shape, I encountered an issue where the height of t ...

Cannot get Firebase's set() method to work when called within onAuthStateChanged() function

As I embark on developing my first significant web application using ReactJS with Firebase as the backend database, everything was progressing smoothly until a troublesome issue surfaced. The hurdle I encountered involves saving user information upon thei ...

Transform the array of objects into different clusters

I am facing a challenge where I have an object returning two arrays of objects from an API. My goal is to transform this data into a new array of objects in order to effectively group the information for the Vue v-select component. For a visual representat ...

A website with two distinct pages, where only the first page is refreshed

I have split the content of my HTML page into 2 separate subpages, based on the references provided below: Multiple distinct pages in one HTML file This is how my code is structured: ... <script> function show(shown, hidden) { document.getEle ...

When making a jQuery + AJAX request, IE8 is causing a null return value

I'm completely stumped as to why this issue is happening. To start, the code has been checked and validated by the W3C validator as HTML5, except for some URL encoding problems (such as & needing to be &amp;), but I don't have the ability ...

Sending data over a network using Socket and node.js

Trying to update a location on a Google Map using socket.io and node.js. I have 2 different methods for updating the map. There may be some basic issue as I am new to this. 1) Method using an API call that works: app.post('/location', function( ...

Retrieve all the records from the collection that have a specific reference number in their ID field

Is it feasible to pull together all documents with an ID that includes a specific value? I am working with Angular 7. I attempted using db.collection('items').where.. but unfortunately, this method is not supported. For instance: (collection) ...

Achieve the effect of "background-attachment: fixed" using a div element

I am attempting to replicate a similar effect as seen here, which is accomplished using the CSS property background-attachment:fixed. However, I want to achieve this effect using div elements instead. For instance, could I apply this effect to an h1 tag? ...

Ways to link a Javascript or Jquery function to an HTML form

I am looking to develop a form that can extract email addresses from input text. While I know there are many scripts available that can do this quite easily, my goal is to create one on my own. After reading, researching, and experimenting with differ ...

Using the scroll feature within the tooltip component in React with @material-ui/core/Tooltip can cause the entire page to

I am currently working with a tooltip created using the @material-ui/core/Tooltip library, and it is functioning correctly. You can see an example of the tooltip in action at this link: https://codesandbox.io/s/kgccc. https://i.stack.imgur.com/fMgGb.png ...

Customize your website with eye-catching full width colored blocks using Bootstrap 3

I am in need of colorful full-width blocks to differentiate the sections on my website. Currently, I am constructing my website with Bootstrap 3 within a standard container. However, I would like certain sections to be vibrant blocks that span across the ...

Tips for ensuring that images fully occupy my carousel slides

I am struggling to make my images fit properly within the slides. Here is the code snippet I have tried along with some screenshots: <div className="relative h-24 w-20 sm:h-44 sm:w-100 md:h-44 md:w-60 flex-shrink-0"> <Carousel showThu ...

Challenge implementing custom javascript to display categorical/string features on Shiny slider

I'm attempting to design a unique Shiny slider that represents the months of the year. My desired outcome is for the slider to display the names of the months as strings, rather than numeric values where 1 corresponds to January, 2 corresponds to Febr ...

Executing a RESTful API request with Mocha in a Node.js environment

I've been attempting to make a REST call using Mocha. I tried using the "request" framework to log in at auth0. The REST call is correct; I tested the same data in Postman and received the correct response. However, when trying to implement the call ...

Trouble with implementing a stationary header for a table on IE9?

I have successfully created a table with a fixed header and scrollable content. I utilized CSS classes "fixedHeader" for thead and "scrollContent" for tbody: thead.fixedHeader tr { position: relative; } html > body thead.fixedHeader tr { displa ...

What advantages can be gained by opting for more precise module imports?

As an illustration, consider a scenario where I have an Angular 6 application and need to bring in MatIconModule from the @angular/material library. Two options could be: import { MatIconModule } from '@angular/material/icon'; Or import { Mat ...

How can I divide a div by utilizing word wrap?

My CSS-styled div is pretty straightforward .text { text-transform: capitalize; color: #FFFFFF; background: #918a8a; opacity: 0.6; font-size: 2em; height: 80px; width: 200px; } It creates a grey box w ...