Home > Mobile >  How to check every value meets condition in Javascript function?
How to check every value meets condition in Javascript function?

Time:11-22

I'm building a Vuejs & Laravel app and have a list of data called "questions" which I am trying to iterate through and see if the answer value within the question is not equal to null. If even a single question's answer value is null, I want to prevent the form from submitting and use an alert to tell the user to fill in all questions.

The issue I'm having is even though all the answers are not yet filled out, I still get a 'success' logged in the console from my function.

Can anyone point out where I am going wrong with this?

This is my list of data:

enter image description here

As you can see, some of the answer fields are null, whereas if they are filled out there is data there.

And this is my submit function which I have bound to my form 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');
                    }
                })
            })}
                
        
    },

Thanks in advance!

CodePudding user response:

You should return a truthy value inside every.

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

            if (check) {
                // every answer has been filled
            } else {
                // some answers are missing
            }
        })
    }
}

CodePudding user response:

You can do it in several different ways. One is to use some() on the array.

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

Details on more() can be found at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

  • Related