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>
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
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 nameOr if you want to reset the field based on type and you have boolean and other field types in that case
For more type info see here
A basic
vuejs
template and script sample would look as followSee ow the
@submit.prevent="onSubmit"
is used in the form element. That would by default, prevent the form submission and call theonSubmit
function.Let's assume we have the following for the above
You can call the
resetForm
from anywhere and it will reset your form fields.This solution is only for components
If we toggle(show/hide) components using booleans then data is also removed. No need to clean the form fields.
I usually make components and initialize them using booleans. e.g.
When use clicks on edit button then this boolean becomes true and after successful submit I change it to false again.
For reset all field in one form you can use
event.target.reset()
Markup
Script
Read the difference between a deep copy and a shallow copy HERE.
What you need is to set
this.text
to an empty string in yoursubmitForm
function:Remember that binding works both ways: The (input) view can update the (string) model, or the model can update the view.