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>
To clear all the input in an HTML form, use the <input> tag with the type attribute as reset.
In vue. js, we use the v-model directive to create a two-way data binding between the input field and vue data property, so that we can clear an input field value by setting the empty string (" ") to the data property. Here is an example that clears the input value by clicking on a Reset button.
To clear an input field after submitting: When the button is clicked, set the input field's value to an empty string. Setting the field's value to an empty string resets the input.
There are three ways to reset component state: Define key attribute and change that. Define v-if attribute and switch it to false to unmount the component from DOM and then after nextTick switch it back to true. Reference internal method of component that will do the reset.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With