0

I would like to validate at least one need to check the checkbox. I'm trying to validate when I clicked on checkbox through the loop. When I checked one, the output is invalid return false in the first click. When I unchecked return true. But when I checked my sizes array data with vue-dev tools data is valid. I'm trying to find that bugs but I didn't find. I don't know why.I would like to know that's why? Am I wrong?

new Vue({
  el: '#app',
  data: {
   		sizes:[
      	{id:1,name:'small',ischeck:false,price:0},
        {id:2,name:'medium',ischeck:false,price:0},
        {id:3,name:'large',ischeck:false,price:0}        
      ],
      newval:[]
  },
  methods: {
    checkchanged(){
    	for(var i=0;i<this.sizes.length;i++){           
      	console.log(this.sizes[i].ischeck);
      }     
      
    }
  }
})
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>

<div id="app">
<span v-for="size in sizes">
  <input type="checkbox" v-model="size.ischeck" :value="size.ischeck" 
    @click="checkchanged">
    <label>{{size.name}}</label>
    <input type="text" :disabled="!size.ischeck" v-model="size.price">
</span>

</div>

0

1 Answer 1

1

You could do that using computed property which you call error and hide/show the error message according to that property value:

new Vue({
  el: '#app',
  data: {
   		sizes:[
      	{id:1,name:'small',ischeck:false,price:0},
        {id:2,name:'medium',ischeck:false,price:0},
        {id:3,name:'large',ischeck:false,price:0}        
      ],
      newval:[],
      
  },
  methods: {
    checkchanged(){
    	for(var i=0;i<this.sizes.length;i++){           
      	console.log(this.sizes[i].ischeck);
      }  
      
    }
  },
  computed:{
    error(){
      for(var i=0;i<this.sizes.length;i++){ 
      if(this.sizes[i].ischeck) return false;
    }
    return true;
    }
  }
})
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>


<div id="app"  style="display :flex;flex-direction: column;">
<div v-for="size in sizes">
  <input type="checkbox" v-model="size.ischeck" :value="size.ischeck" 
    @change="checkchanged">
    <label>{{size.name}}</label>
    <input type="text" :disabled="!size.ischeck" v-model="size.price">
    
</div>
   <div v-if="error"  style="color:red">
     there's an error !
   </div>
</div>

Finally you don't need to that event @click="checkchanged" you can use @change="checkchanged" instead

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

Comments

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.