Home > front end >  How to get Please select to show in a dropdown box in vue
How to get Please select to show in a dropdown box in vue

Time:01-27

I have this form that has a dropdown box. Everything works fine except if you have "Please Select" selected it saves the value of it which is 0 to the database and because of that when I go to the page that displays the product, the page breaks because it can't find the category.

Here is my code

<template>
    <div>
        <select  v-model="newCategory">
            <option value="0" selected>Please Select</option
            <option v-for=category in categories" :value=category.id>
                {{ category.name }}
            </option>
        </select>

        <button  @click="save">Save</button>
    </div>
</template>

<script>
    export default {
        props: ['categories'],
        data() {
            return {
                newCategory: 0
            }
        },
        methods: {
            save(){
                axios.post('/api/products/create', {
                    category: this.newCategory
                }).then(response => {
                    this.newCategory = 0;
                });
            }
        }
    }
</script>

CodePudding user response:

just check your this.newCategory before you send request to server and if it was 0 show a toast or something.

code should be like this:

save(){
if(this.newCategory === 0) show something and return;
// bottom codes will be shown only in else section
            axios.post('/api/products/create', {
                category: this.newCategory
            }).then(response => {
                this.newCategory = 0;
            });
        }

CodePudding user response:

First you need to make your newCategory field accept null values, because you need to populate it even if you are saving data without selecting option. Then try the following:

<select v-model="newCategory">
  <option value="" disabled selected>Select your option</option>
  <option v-for=category in categories" :value=category.id>
    {{ category.name }}
  </option>
</select>


data() {
 return {
   newCategory: null
 }
},
  •  Tags:  
  • Related