Is it possible to verify if each value satisfies a condition within a Javascript function?

I am currently working on a project using Vue.js and Laravel where I have a data list named "questions." My goal is to iterate through this list and check if the answer value for each question is not null. If any question has a null answer, I want to prevent the form from submitting and notify the user to fill in all questions with an alert message.

However, I am facing an issue where even though some answers are still empty, the console logs 'success' when the function executes.

If anyone can help me identify where I went wrong with my approach, I would greatly appreciate it.

Here is the data list I am working with:

https://i.stack.imgur.com/1r7TH.png

As shown in the image, there are some null values in the answer fields that need to be filled out.

Below is the submit function that is linked to the form's submit button:

methods: {
        submitPressed(e){
            console.log(this.questions);
            this.questions.forEach(question => {
                question.questions.every(q => {
                    if(q.answer !== null){
                        console.log('success');
                        // this.submit();
                    } else {
                        e.preventDefault();
                        console.log('more to fill out');
                    }
                })
            })}
                
        
    },

Thank you in advance!

Answer №1

It is important to ensure that a truthy value is returned within the every function.

methods: {
    submitPressed(e){
        this.questions.forEach(question => {
            const check = question.questions.every(q => {
                if (q.answer !== null) {
                    return true;
                } else {
                    return false;
                }
            });

            if (check) {
                // All answers have been provided
            } else {
                // Some answers are still missing
            }
        })
    }
}

Answer №2

There are multiple approaches to achieve this task. One method involves utilizing the some() function on the array.

methods: {
   submitPressed(e) {
      console.log(this.questions);
      if (this.questions.some(q => !q.answer)) {
         e.preventDefault();
         console.log('more information required');
      } else {
         console.log('successful submission');
         // this.submit();
      }
   }
},

For further information on some(), visit https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

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

A type error was thrown: $.ajax function does not exist within another function

I encountered a persistent ajax error on the website. Error : Uncaught TypeError: $.ajax is not a function at Hei Here is my code for reference: Can anyone pinpoint where I may be going wrong? The suggested solutions from other sources have not resol ...

Embed JavaScript locally within an iframe HTML

When attempting to add HTML code within an iframe to showcase data, everything works as expected. However, the issue arises when trying to include any JavaScript within the iframe, as it doesn't seem to be recognized locally. Below is the example cod ...

AngularJS filtering with multiple conditions

My ng-repeat list is currently displaying a collection of objects with a filter applied to only show objects inserted today. Here is how it looks: <div class="row msf-row" ng-repeat="record in recordlist | filter: record.date = dateJson"> Whi ...

What causes the function execution to not be delayed by setTimeout?

function attemptDownloadingWebsite(link) { iframe = document.getElementById('downloadIFrame'); iframe.src = link; setTimeout(removeFile(link), 25000); } This is the remove file function: function removeFile(link){ $.ajax ...

Updating React component props

After updating the state in a component and passing the new props into the child, I noticed that the child is not updating correctly and the defaultValue of the input is not changing. My initial thought was that using this.props could be the issue, so I sw ...

Can all intervals set within NGZone be cleared?

Within my Angular2 component, I have a custom 3rd party JQuery plugin that is initialized in the OnInit event. Unfortunately, this 3rd party library uses setIntervals extensively. This poses a problem when navigating away from the view as the intervals rem ...

Iterate over a JSON array using jQuery

I am attempting to iterate through this data to extract the 'name' values. Here is my current code, but it does not seem to be functioning correctly. I have tried a few variations from suggestions here, but none of them have worked. $.get("/ ...

Implementing dynamic https URL embedding in AngularJS based on the user's browser location

When my webpage built with angularjs is launched using https, all urls within the page should also use https instead of the default http. Is it possible to make angularjs use either http or https based on the initial request? Here are some example embedd ...

Exploring the Power of Two jQuery Ajax Functions in Your Script

Is it possible to provide guidance on how I can successfully execute two separate Ajax calls within a single script without encountering conflicts? A sample of the current script structure is as follows: <script type="text/javascript"> $(document).r ...

What are the steps to effectively utilize the $filter('filter') function when filtering multiple columns with OR as the condition?

In my AngularJs Application, I have a collection of customers. var customers = [ { "Name": "Alfreds Futterkiste", "City": "Berlin", "Country": "Germany" }, { "Name": "Ana Trujillo Emparedados y helados", ...

Error encountered when running the production build server for android in Meteor: TypeError - Unable to access property 'slice' of null

Here's a demo I'm working on: https://github.com/pc-magas/pupAndroidDemo I'm trying to build this demo for Android. I've already installed the Android SDK and configured the necessary environmental parameters. Following the instructio ...

Eliminate elements from an array using a specific key for filtering

My Array is called MainArray MainArray=[{ {First Name: "First Name"}, {Last Name: "Contact"}, {Last Name: "Contact"} ] I am trying to trim the key-value pair from this array like this: if (key == 'First Name') { del ...

Tips for assessing JSON response data from an AJAX form

I am struggling with how to properly structure a question, but I would like to explain my situation. I am using AJAX to send data and receiving JSON in return. Each value in the JSON response represents a status, and I need to test and react based on these ...

What is the method to conceal an element after detecting and locating a specific class using jQuery?

Can someone please assist me today with the following task: Step 1: <div id="htmlData"> <div class="col-md-12"> <div class="pull-left"> <h3>Report: <strong>Travel </strong></h3> ...

Adjusting the maxContentLength and maxBodyLength values in Axios

While utilizing the "Axios" library to invoke a WCF method with file information and content as parameters, I encountered an issue. The file is read and transmitted as a base64 encoded string. However, when the file size surpasses a specific limit, Axios t ...

In the `angular-daterangepicker.js` file, add the option "Single Date" to the list of available ranges

I'm currently working on implementing a new feature that is similar to the "Custom Range" option, but with a twist. I want to provide users with the ability to choose only one date, much like a "Single Date Picker". By adding this new option under "Cu ...

Struggling to display the sorted array items on the screen?

Within the realm of my jsfiddle experiment, my aim is to organize items based on price from highest to lowest by utilizing the following function: function mySortingFunction() { var elements = [].slice.call(document.getElementsByClassName("price")); e ...

I have to make sure not to input any letters on my digipas device

There is a slight issue I am facing. Whenever I input a new transfer of 269 euros with the bank account number BE072750044-35066, a confirmation code is required. The code to be entered is 350269. https://i.stack.imgur.com/YVkPc.png The digits 350 corres ...

Tips for integrating CKEditor into an Angular 4 project

To start using CKEditor, I first installed it by running the command npm install ng2-ckeditor. Next, I included ckeditor.js in my index.html file. I then imported { CKEditorModule } from 'ng2-ckeditor'; in my app.module.ts file. After setup, I ...

An issue arose during the page prerendering process for "/" on Vercel | Next.js resulting in a deployment error

When attempting to deploy my website using Vercel and generating static pages, I encountered the following error in the logs: info - Generating static pages (0/6) Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/ ...