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 for me to modify this carousel so that it only stops when a user hovers over one of the boxes?

I am currently working to modify some existing code to fit my website concept. One aspect I am struggling with is how to make the 'pause' function activate only when a user hovers over one of the li items, preventing the carousel from looping end ...

Concerning the issue of components not loading correctly when using Angular with Lazy Loading Routing

Encountering an unusual issue while utilizing lazyload routing in our application! Within AppModule, there is TopModule followed by DashboardModule, all being loaded lazily. When localhost:4200/dashboard is accessed, the loading sequence is AppModule, To ...

What is the best place to define data that remains constant?

In a Vue component, I am looking to utilize data that remains constant. The issue arises when attempting to implement the following code: const numbers = [1, 2, 3] new Vue({ el: "#app" }) <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2 ...

Error: JSON at position 1 is throwing off the syntax in EXPRESS due to an unexpected token "

I'm currently utilizing a REST web service within Express and I am looking to retrieve an object that includes the specified hours. var express = require('express'); var router = express.Router(); /* GET home page. ...

OceanWP Theme with a Fixed Navigation Bar

Currently utilizing the oceanwp theme, I'm aiming to create a topbar that vanishes while scrolling and have the menu smoothly transition to the topbar location with some opacity. I attempted the following code snippet: #site-header { position: fixe ...

What is the way to execute a function *once* all my ajax call functions have finished?

I am utilizing jQuery to execute some ajax requests: var information = {}; function process_information(item){ information[item.id] = item; } function perform(){ var calls = []; for(var i = 0; i < 10; i++){ var call = $.get(URL, ...

Having trouble making .click() function work in jQuery

Struggling with translating my javascript code to jQuery for homework. The .click function is causing me some serious issues. Here's a snippet of the code I'm working on: (document).ready(function() { $("start_test").click (function() { ...

A step-by-step guide on connecting an event listener to the search input of Mapbox GL Geocoder in a Vue application

I've encountered a challenge trying to add an event listener to the Mapbox GL Geocoder search input within a Vue application. It appears to be a straightforward task, but I'm facing difficulties. My objective is to implement a functionality simi ...

Why is AJAX failing to execute PHP file from JavaScript?

The Issue: Hello, I have confirmed that my PHP file is functioning properly. However, the AJAX code connected to my JavaScript function seems to be malfunctioning. Even though the function is triggered, nothing happens as expected. The Script: Check o ...

Tips for identifying the version of a package that is installed using a package-lock.json file containing lockfileVersion = 3

After upgrading from Node 16 (npm 8) to Node 18 (npm 9), I noticed a difference in the structure of the package-lock.json files. Files generated with npm 8 have a lockfileVersion: 2, while those generated with npm 9 have a lockfileVersion: 3. The changes a ...

Guide on transferring JSON information from a client to a node.js server

Below is the code snippet from server.js var express = require("express"), http = require("http"), mongoose = require( "mongoose" ), app = express(); app.use(express.static(__dirname + "/client")); app.use(express.urlencoded()); mongoose.con ...

Sidenav Content with all elements having opacity applied

How can I ensure that all page elements have a black background color when the mobile navigation is opened on the left screen, while ensuring that my sidebar and content image do not get overlaid by the black background? Here is my code: function openNav( ...

What are the possible arguments for the event type onInput?

While diving into the world of html / javascript / vue, I stumbled upon the following code snippet. <input type="text" onInput="doAction(event);"> <script> var mesdata = { message: 'type your m ...

Express: SimpleAuth

I've been attempting to set up basic authorization for the endpoints in my express app using express-basic-auth, but I keep getting a 401 unauthorized error. It seems like the headers I'm sending in Postman might be incorrect: Middleware: app.u ...

Determine the height using jQuery before adding the class

I've been grappling with jQuery to accurately calculate the height of an element and then apply a specific CSS class to adjust its height. The issue I'm facing is that jQuery seems to be executing these calculations out of order, which is causing ...

Error in routing of submit button in Express.js

While attempting to create a basic "to-do list" using HTML requests, I encountered an issue with the PATCH request. Instead of redirecting to "/", it redirected to "/posts/2" and displayed the message "Cannot POST /posts/2", without updating the array elem ...

When conducting tests using Selenium and the headless Google Chrome browser in Java, the dynamic JS content fails to load

Currently, I am in the process of testing a website that I have developed as part of a Spring Boot project using Selenium. While I can successfully test basic functionalities such as page loading and title verification, I am encountering difficulties when ...

Utilizing Node.js within a closed intranet environment

Utilizing Nodejs's npm has proven to be quite convenient. Thus, I made the decision to incorporate it into my company's project. However, a predicament arises as my company mandates development within a closed network. This restricts my access s ...

Scroll-triggered Autoplay for YouTube Videos using JQuery

Issue: I'm trying to implement a feature where a YouTube video starts playing automatically when the user scrolls to it, and stops when the user scrolls past it. Challenges Faced: I am new to JavaScript web development. Solution Attempted: I referre ...

Retrieving Checkbox Values in PHP: A Step-by-Step Guide

Question: Retrieving values from a checkbox I am facing an issue with the script below where I am only able to retrieve the last selected value of the checkbox. How can I modify the code to fetch all the selected values for validation purposes? Here ...