Clearing input in vuejs form

140,195

Solution 1

What you need is to set this.text to an empty string in your submitForm function:

submitForm(e){
    this.todos.push(
        {
            text: this.text,
            completed: false
        }
    );
    this.text = "";

    // To prevent the form from submitting
    e.preventDefault();
}

Remember that binding works both ways: The (input) view can update the (string) model, or the model can update the view.

Solution 2

These solutions are good but if you want to go for less work then you can use $refs

<form ref="anyName" @submit="submitForm">
</form>

<script>
   methods: {
      submitForm(){
         // Your form submission
         this.$refs.anyName.reset(); // This will clear that form
      }
   }
</script>

Solution 3

Assuming that you have a form that is huge or simply you do not want to reset each form field one by one, you can reset all the fields of the form by iterating through the fields one by one

var self = this;
Object.keys(this.data.form).forEach(function(key,index) {
    self.data.form[key] = '';
});

The above will reset all fields of the given this.data.form object to empty string. Let's say there are one or two fields that you selectively want to set to a specific value in that case inside the above block you can easily put a condition based on field name

if(key === "country") 
   self.data.form[key] = 'Canada';
else 
   self.data.form[key] = ''; 

Or if you want to reset the field based on type and you have boolean and other field types in that case

if(typeof self.data.form[key] === "string") 
   self.data.form[key] = ''; 
else if (typeof self.data.form[key] === "boolean") 
   self.data.form[key] = false; 

For more type info see here

A basic vuejs template and script sample would look as follow

<template>
  <div>
    <form @submit.prevent="onSubmit">
      <input type="text" class="input" placeholder="User first name" v-model="data.form.firstName">
      <input type="text" class="input" placeholder="User last name" v-model="data.form.lastName">
      <input type="text" class="input" placeholder="User phone" v-model="data.form.phone">
      <input type="submit" class="button is-info" value="Add">
      <input type="button" class="button is-warning" @click="resetForm()" value="Reset Form">
    </form>
  </div>
</template>

See ow the @submit.prevent="onSubmit" is used in the form element. That would by default, prevent the form submission and call the onSubmit function.

Let's assume we have the following for the above

<script>
  export default {
    data() {
      return {
        data: {
          form: {
            firstName: '',
            lastName: '',
            phone: ''
          }
        }
      }
    },
    methods: {
      onSubmit: function() {
        console.log('Make API request.')
        this.resetForm(); //clear form automatically after successful request
      },
      resetForm() {
        console.log('Reseting the form')
        var self = this; //you need this because *this* will refer to Object.keys below`

        //Iterate through each object field, key is name of the object field`
        Object.keys(this.data.form).forEach(function(key,index) {
          self.data.form[key] = '';
        });
      }
    }
  }
</script>

You can call the resetForm from anywhere and it will reset your form fields.

Solution 4

For reset all field in one form you can use event.target.reset()

const app = new Vue({
    el: '#app',    
    data(){
	return{        
            name : null,
	    lastname : null,
	    address : null
	}
    },
    methods: {
        submitForm : function(event){
            event.preventDefault(),
            //process...             
            event.target.reset()
        }
    }

});
form input[type=text]{border-radius:5px; padding:6px; border:1px solid #ddd}
form input[type=submit]{border-radius:5px; padding:8px; background:#060; color:#fff; cursor:pointer; border:none}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.6/vue.js"></script>
<div id="app">
<form id="todo-field" v-on:submit="submitForm">
        <input type="text" v-model="name"><br><br>
        <input type="text" v-model="lastname"><br><br>
        <input type="text" v-model="address"><br><br>
        <input type="submit" value="Send"><br>
    </form>
</div>

Solution 5

Markup

<template lang="pug">
  form
    input.input(type='text' v-model='formData.firstName')
    input.input(type='text' v-model='formData.lastName')
    button(@click='resetForm') Reset Form
</template>

Script

<script>
  const initFromData = { firstName: '', lastName: '' };
  
  export default {
    data() {
      return {
        formData: Object.assign({}, initFromData),
      };
    },
    methods: {
      resetForm() {
        // if shallow copy
        this.formData = Object.assign({}, initFromData);
  
        // if deep copy
        // this.formData = JSON.parse(JSON.stringify(this.initFromData));
      },
    },
  };
</script>

Read the difference between a deep copy and a shallow copy HERE.

Share:
140,195
Tony
Author by

Tony

Updated on July 21, 2022

Comments

  • Tony
    Tony almost 2 years

    Just completed a todolist tutorial. When submitting the form the input field doesn't clear.

    After trying both:

        document.getElementById("todo-field").reset();
        document.getElementById("#todo-field").value = "";
    

    The input field properly clears but it also deletes the todo.

    It seems to delete the input field before it has time to push the new todo in the todos.text array.

    Would love some input guys! Thanks!!

    <template>
      <form id="todo-field" v-on:submit="submitForm">
        <input type="text" v-model="text">
      </form>
         <ul>
           <li v-for="todo in todos">
            <input class="toggle" type="checkbox" v-model="todo.completed">
            <span :class="{completed: todo.completed}" class="col-md-6">
                <label @dblclick="deleteTodo(todo)">
                    {{todo.text}}
                </label>
            </span>
    
           </li>
         </ul>
    

    <script>
      export default {
        name: 'todos',
          data () {
            return {
              text: '',
              todos: [
              {
          text:'My Todo One',
          completed: false
        },
        {
          text:'My Todo Two',
          completed: false
        },
        {
          text:'My Todo Three',
          completed: false
        }
      ]// End of array
    }
      },
        methods: {
        deleteTodo(todo){
            this.todos.splice(this.todos.indexOf(todo),1);
        },
        submitForm(e){
            this.todos.push(
                {
                    text: this.text,
                    completed: false
                }
            );
            //document.getElementById("todo-field").reset();
            document.getElementById("#todo-field").value = "";
    
            // To prevent the form from submitting
            e.preventDefault();
        }
    }
    }
    </script>