1

When I click to add a button with an empty value, empty value added in the list. Here I have attached a screenshot. I need validation for an empty value. My code is not working.

Error Output: https://prnt.sc/pk0hvt

HTML:

<form
    id="listadding-wrap"
    @submit="checkForm"
    action="#"
    method="post"
>
    <input type="text" class="form-control" v-model="newName">
    <button class="addbtn" @click="addName">+</button>

    <ul class="teamlist">
        <li v-for="teamMember in teamMembers" v-text="teamMember"></li>
    </ul>
    <p v-if="errors.length">
        <b>Please enter the value to add</b>
        <ul>
            <li v-for="error in errors">{{ error }}</li>
        </ul>
    </p>
</form>

Vue JS:

var teammember = new Vue({

    el: '#listadding-wrap',
    data: {
        errors: [],
        newName:'',
        teamMembers: ['']
    },
    methods: { 
        checkForm: function (e) {
            if (this.newName) {
                return true;
            }
            this.errors = [];

            if (!this.newName) {
                this.errors.push('Name required.');
            }

            e.preventDefault();
        },

        addName() {
            this.teamMembers.push(this.newName);
            this.newName = '';
        }
    },

});

1 Answer 1

1

You added 2 event handlers, one at form @submit and another at button @click

Here in the above code, button click triggers first and the form submit

I've moved the logic to submit action instead of two separate events

Here is the working code

For codepen : https://codepen.io/chansv/pen/RwwRgqd

<form
    id="listadding-wrap"
    @submit="checkForm"
    action="#"
    method="post"
>
    <input type="text" class="form-control" v-model="newName">
    <button class="addbtn">+</button>

    <ul class="teamlist">
        <li v-for="teamMember in teamMembers" v-text="teamMember"></li>
    </ul>
    <p v-if="errors.length">
        <b>Please enter the value to add</b>
        <ul>
            <li v-for="error in errors">{{ error }}</li>
        </ul>
    </p>
</form>

var teammember = new Vue({

    el: '#listadding-wrap',
    data: {
        errors: [],
        newName:'',
        teamMembers: [],
    },
    methods: { 
        checkForm: function (e) {
          console.log(e);
            this.errors = [];

            if (!this.newName) {
                this.errors.push('Name required.');
            } else {
              this.teamMembers.push(this.newName);
              this.newName = '';
            }


            e.preventDefault();
        }
    },

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.