Adnan
Adnan

Reputation: 11

Scroll to first error using Vue Validate in b-form

trying to scroll to the first error when submitting a form using Vue Validate for validation in bootstrap form (b-form)

Upvotes: 0

Views: 3164

Answers (1)

Anup Das Gupta
Anup Das Gupta

Reputation: 771

I think you are looking for something like this-

const app = new Vue({
  el:'#app',
  data:{
    errors:[],
    name:null,
    age:null,
    movie:null
  },
  methods:{
    checkForm:function(e) {
      this.$refs.errorP.scrollIntoView();
      if(this.name && this.age) return true;
      this.errors = [];
      if(!this.name) this.errors.push("Name required.");
      if(!this.age) this.errors.push("Age required.");
     
      e.preventDefault();
      
    }
  }
})
input,select {
  margin-left: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<form id="app" @submit="checkForm" action="/something" method="post">
  <div ref="errorP">
  <p v-if="errors.length" >
    <b>Please correct the following error(s):</b>
    <ul>
      <li v-for="error in errors">{{ error }}</li>
    </ul>
  </p>
  </div>
  <div style="height: 1000px;">
  Scroll to the bottom to see the form
  </div>
  <p>
    <label for="name">Name<label>
    <input type="text" name="name" id="name" v-model="name">
  </p>

  <p>
    <label for="age">Age<label>
    <input type="number" name="age" id="age" v-model="age" min="0">
  </p>

  <p>
    <label for="movie">Favorite Movie<label>
    <select name="movie" id="movie" v-model="movie">
      <option>Star Wars</option>
      <option>Vanilla Sky</option>
      <option>Atomic Blonde</option>
    </select>
  </p>

  <p>
    <input type="submit" value="Submit">  
  </p>

</form>

https://jsfiddle.net/anupdg/j24xt7rd/1/

Upvotes: 1

Related Questions