Activate the button when any input is incomplete and deactivate it when all inputs are completed

I need to implement a feature where a button is disabled until all input fields on the page are filled. The challenge is that I must achieve this using only JavaScript without converting the structure to a form as it would interfere with other aspects of the code. Currently, the button turns enable when some inputs are filled (even just one), but if all inputs are completed, the button disables again. It also remains disabled when no inputs have been filled. My goal is to enforce the requirement for all inputs to be filled before enabling the button, ensuring that users cannot submit the form empty or with partially completed fields.

The JavaScript code below demonstrates how input validation is achieved:

document.addEventListener('DOMContentLoaded', function(){
    const required = document.querySelectorAll('.input');

    function checkSubmit(button){
        let isValid = true;
        for(let i = 0; i <required.length; i++){
            isValid = isValid && !!required[i].value;
            console.log("is enabled");
        }
        button.disabled = isValid;
        console.log("is disabled");
    }

    function inputHandler(button){
        return function(){
            checkSubmit(button);
        };
    }

    // Get all quiz buttons                                                                                                                                      enableChecking();
    const quizButton = document.querySelectorAll('.quiz_button');
    for (const button of quizButton){
        button.disabled = true;
        for(let i = 0; i <required.length; i++){
            required[i].addEventListener("input", inputHandler(button));
        }
        button.addEventListener('click', (event) =>
            check_quiz(event.target.id));
    }
});

Answer №1

I have updated and streamlined the code for you so that it functions as intended. Now, all buttons will only become enabled once all input fields have been filled.

  document.addEventListener('DOMContentLoaded', function () {
  const inputs = document.querySelectorAll('input');
  const quizButtons = document.querySelectorAll('button');

  for (const i of inputs) {
    i.addEventListener("input", checkSubmit);
  }

  for (const b of quizButtons) {
    b.disabled = true;
    b.addEventListener('click', (event) =>
      check_quiz(event.target.id));
  }

  function checkSubmit() {
    let isValid = true;
    for (const i of inputs) {
      isValid = isValid && !!i.value;
    }

    for (const b of quizButtons) {
      b.disabled = !isValid;
    }
  }

});

Feel free to view a live demonstration of this code in action on this jsfiddle link.

I hope this solution is helpful!

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

Reverse the color of H1 text within a vertical div

Is it feasible to reverse the coloring of a segment within an h1 element using a div, horizontally? Refer to the illustration shown in the image below. https://i.sstatic.net/QAKwD.jpg ...

Loading images from a server asynchronously using Javascript

I am currently facing an issue with loading images from my server to an image gallery. The problem is that when the web page loads, all the images are fetched and then displayed simultaneously, leading to a significant delay in loading time. My goal is to ...

I am experiencing issues with my React DND implementation in Next JS - can anyone help troubleshoot?

I'm encountering an issue with my React DND implementation. Although I am able to drag elements, they are not being received by the drop targets. I even tried using console.log in the drop function of useDrop but nothing is logging in the console on d ...

Organize JSON data in Angular 6 from an observable based on a specific key

Note: While I am familiar with sorting a regular array of objects using .sort(), I am facing a challenge with an observable object that I am not accustomed to. My task involves retrieving a JSON array of objects with a service: import { Injectable } from ...

Using a shortcode as a variable in WordPress can enhance the functionality and customization

I have a button shortcode set up on my website that I want to use consistently across all of my posts. My goal is to be able to update the button's details centrally so that any changes made will be reflected in every instance without having to go thr ...

Guide on creating and dynamically appending an element to the DOM in VueJS triggered by a user clicking a button

I'm having an issue with my vue webapp. I want to make a square shape appear on the screen where a user clicks, but for some reason, my code isn't working as intended. Can someone help me figure out what's wrong? <template> <di ...

Load data into data tables through AJAX request

I'm currently working on implementing datatables and I'm facing an issue with populating my data table using an AJAX call. Here is the snippet of my AJAX call: $('#call_analysis_basic_table').DataTable ({ "ajax": { "url": " ...

Harnessing the power of Vue.js within an Nw.js project, sans bundlers: Unveiled

I am currently developing a software application using NW.js and Vue.js. I have decided to build the application without reliance on compilers or bundlers. Although I have successfully installed the Vue.js library via npm, I am facing an issue where it i ...

Updating ng-init in AngularJS triggered by a changeOR Changing

Is there a way for ng-init to be updated when the tableCells change? I'm looking for a method that will avoid angular from calling findCellsByDate twice. I've also attempted changing ng-init to ng-bind or ng-model, but ng-bind displays [object O ...

Navigational menu header leads to specific location on the page

I need the dropdown menu header to both open the related menu and display the content of the first element of the submenu, which is an anchor link on the page. Here is the HTML code for the Dropdown Menu: <div class="collapse navbar-collapse" id="myNa ...

Incorporate AngularJS {{expression}} into ng-repeat by utilizing a separate array

After completely rebuilding my website (which was originally hacked together with Wordpress), I decided to utilize Laravel and AngularJS. The transition has been quite challenging, but I'm almost there, except for one issue. On my website, I have &ap ...

Tips for defining the operational scope of orbit controls in three.js

I've been working on creating an orientation cube in threeJS and have set up 2 scenes with different viewports, cameras, and controls. Check out the fiddle here var controls = new THREE.OrbitControls( view.camera, container.domElement ); In the fid ...

Tips for creating an API URL request with two search terms using Angular and TypeScript

I have developed a MapQuest API application that includes two input boxes - one for the "from" location and another for the "to" location for navigation. Currently, I have hardcoded the values for these locations in my app.component file, which retrieves t ...

Sliding in a strange way

Are you experiencing a strange behavior with the slider on your website? When you hover over the image, the caption at the bottom slides up and on mouseout it slides down again. It works perfectly on . However, when navigating to portfolio via the menu on ...

Convert a list to a JSON object utilizing the Json.NET library

I am using json.net to convert currency rates to JSON format. In the C# entity, there are Name and Value properties; where Name represents currencies like USD, GBP, etc. and Value holds the currency rate. Since I do not know the index of different curren ...

Error encountered: wkhtmltopdf Timeout Issue

I have a unique application that allows users to generate PDFs from HTML using a node server. This application utilizes the wkhtmltopdf 0.12.3-dev-79ff51e engine (with patched qt) integrated with node-wkhtmltopdf module. Occasionally, an error message po ...

Implementing Bootstrap Datepicker within the dynamically generated table rows

I am currently in the process of developing a data grid for a project and I am encountering an issue with implementing Bootstrap Datepicker on the Date field within the table. The problem arises when trying to use the datepicker on subsequent rows that are ...

Is there a way to manipulate the DOM without relying on a library like jQuery?

My usual go-to method for manipulating the DOM involves jQuery, like this: var mything = $("#mything"); mything.on("click", function() { mything.addClass("red"); mything.html("I have sinned."); }); Now I am looking to achieve the same result usin ...

Struggling to navigate web pages with Selenium using Java is proving to be a challenge

I am currently working on using Selenium's HtmlUnitDriver and WebElement classes in Java to automate clicking the "Download as CSV" button on Google Trends. The issue that I am encountering is that the button remains hidden until another settings men ...

The header that sticks on scroll is annoyingly blocking the content

I managed to create a sticky on-scroll header/navigation bar successfully. Here is how it looks now However, I encountered an issue. When it reaches the top, it automatically 'covers' the top part of my content, which has text on it, and I don& ...