0

I am trying to get the array values from "validateBeforeSubmit" function to "saveForm" function. But I am getting values of "undefined" in "arrlength". Please help me to solve.

This my code in vue.js

export default {
  name: '',
  data() {
    return {}
  },
  ready: function() {
    this.validateBeforeSubmit()
    this.saveForm();
  },
  methods: {
    validateBeforeSubmit() {
      var fieldsVal = new Array();
      var firstName = document.getElementById('firstName').value
      var lastName = document.getElementById('lastName').value
      var designation = document.getElementById('designation').value

      if (firstName != "" && lastName != "" && designation != "") {
        fieldsVal.push(firstName);
        fieldsVal.push(lastName);
        fieldsVal.push(designation);
        return fieldsVal;
      } else {
        fieldsVal.length = 0;
        return fieldsVal;
      }
      return fieldsVal;
    },

    saveForm() {
      var fieldsValArray = this.validateBeforeSubmit();
      var arrLength = fieldsValArray.length;
    }
  }
}

1 Answer 1

5

I can see multiple issues in your code:

1) Don't apply jQuery-like approach for getting input values. Use v-model instead. This will simplify your code

<template>
  <input v-model="form.firstName" type="text"/>
</template>
<script>
export default {
  data: {
    form: { 
      firstName: '',
    }
  },
  methods: {
    validateBeforeSubmit() {
      // take `firstName` directly from `data` not need for `getElementById`
      const firstName = this.form.firstName;
    }
  },
}
</script>

2) Remove validateBeforeSubmit and saveForm from ready. Ready hook is obsolete in vue@2. And also it makes no sense. It's better to call it on form @submit.

3) It's better to create array using [] syntax instead of new Array()

Why never use new Array in Javascript

4) Always provide name for your component for easier debug

export default {
   name: 'ValidationForm',
}

5) I don't know where was an issue but it works. Check this link below. I have updated your code. Try to submit form and check the console:

https://codesandbox.io/s/w6jl619qr5?expanddevtools=1&module=%2Fsrc%2Fcomponents%2FForm.vue

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer. If you have enough time kindly answer for my another question & the question link is: question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.