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

Is there a more efficient alternative to the sluggish scroll event?

Currently, I have set up a scroll event that tracks the user's position on the page and updates the navigation styling based on which section they are viewing. However, the calculation I'm using during scrolling is quite resource-intensive and ca ...

Retrieving all buttons from a webpage and removing those with a specific background-image using JavaScript

Hey everyone, I'm still learning about javascript and other web development languages. My current task is to locate all the buttons on a webpage and remove the ones that have a specific background image. I know about using getElementsByTagName but n ...

Retrieving Twitter posts using the screen_name parameter in a Node.js environment

I am looking to create a website that allows users to enter the Twitter screen name of any celebrity. When the user clicks on the "show tweet" button, the latest tweet from that screen name will be displayed. I am interested in implementing this feature ...

The Next.js application encounters a crash when trying to integrate Google Firebase authentication

I'm encountering an issue while trying to integrate authentication using firebase (via Google) in my next.js application, and the app crashes consistently. I will provide the code for the auth.js page component, as well as where I set up firebase and ...

Unable to add key/value pair to object in Node

While using Node, I encountered a strange issue where I was unable to attach the key/value pair broadcastStamp = date to the object "result." Despite confirming that it is indeed an object with typeof, no errors were thrown - the key/value simply did not a ...

Pass the returned variable value from a request.get call to another function in NodeJS Express

I have a situation where I am calling a function that makes a request to get some JSON data and then fills in the variables from my router.get method. The issue I am facing is that the variables are getting their value inside the callFunc function, but wh ...

CustomTooltips in ChartJS allowing for an enhanced visual presentation of data

I am encountering an issue with my code where I am trying to incorporate images into custom tooltips. The goal is to dynamically generate PNG filenames based on the tooltip name or ID, but I am struggling to find unique values to assign as filenames for ea ...

"Preventing premature access: how to handle the 'must not be accessed before initialization' error in Laravel Livewire

I am attempting to utilize Livewire Binding Directly To Model Properties, but I encountered the following error message. Can anyone please assist me with this issue? Thank you in advance. Typed property App\Http\Livewire\V2\Settings&b ...

Error-free ngClick doesn't trigger AngularJS controller method

I am struggling to trigger the removePlayer(playerId) method upon clicking a button. However, it seems that the method is not being called, as I have placed a console.log() statement at the top and the console remains empty. This situation has left me puz ...

Having trouble with setting up the next image configuration for graphcms' images

I've been using graphcms solely for my image assets and trying to integrate them into my Next JS (v12.0.1) frontend. However, I keep getting the error message hostname not configured in next.config.js, even though I have already specified it in my nex ...

using brackets to access objects in Vue.js

My function is designed as follows: field_validator(rule, value, callback) { this.form.setFieldsValue({ [rule.field]: null }) } I encountered an issue where I couldn't create the object like { rule.field: null }, and instead had to use brackets ...

Verify if the array entries match

Within my select element, I populate options based on an array of values. For example: [{ name: 'A', type: 'a', }, { name: 'B', type: 'b', }, { name: 'B', type: 'b', }, { name: &apos ...

Utilize the "incorporate" feature to include any string within an array

I am currently working on improving the search function in my application. This particular search function takes input from a search bar and is designed to handle multiple search terms. For example, it should be able to handle queries like "javascript reac ...

Unveiling the mysteries of JSONP in conjunction with AJAX

JSONP allows for bypassing the same origin policy in JavaScript by using <script> tags to load third party data. However, I am uncertain about how JSONP is utilized together with AJAX. My assumption is that: When an AJAX call is initiated, a <sc ...

Adjust the anchor tag content when a div is clicked

I have a list where each item is assigned a unique ID. I have written the HTML structure for a single item as follows: The structure looks like this: <div id='33496'> <div class='event_content'>..... <div>. ...

Switching back and forth between celsius and fahrenheit using jQuery (my mistake in the code)

I am currently using Ajax to interact with the openweather API. Everything seems to be functioning correctly except for one issue. My goal is to create a button that toggles between displaying temperature in Celsius and Fahrenheit. When I click the button ...

Organizing Parsed JSON Data with JavaScript: Using the _.each function for Sorting

var Scriptures = JSON.parse( fs.readFileSync(scriptures.json, 'utf8') ); _.each(Scriptures, function (s, Scripture) { return Scripture; }); This code extracts and displays the names of each book from a collection of scriptures (e.g., Genesis, ...

When removing an item using its key, the vue component does not automatically refresh

I'm attempting to remove an object by its key and expecting the component to update accordingly using Vuex. Here is my current approach: The structure of my objects is as follows: 115:Object 116:Object I have the keys (115, 116) and I am t ...

Guide to locating and substituting two integer values within a string using JavaScript

Given a string such as: "Total duration: 5 days and 10 hours", where there are always two integers in the order of days and then hours. If I need to update the old string based on calculations using fields and other values, what is the most efficient meth ...

Protractor - I am looking to optimize my IF ELSE statement for better dryness, if it is feasible

How can I optimize this code to follow the D.R.Y principle? If the id invite-user tag is visible in the user's profile, the user can request to play a game by clicking on it. Otherwise, a new random user will be selected until the id invite-user is di ...