How to Clear Input Field After Submit
After users submit an input, they need to clear the current input field to give another input, so it impacts the user experience. When it comes to web forms, a common challenge we face is how to clear input fields after submitting the form. The solution to this problem can be clearly found in this article.
In the example below, we have created a todolist in which users have to clear the current input to submit another task after submitting a task type.
HTML:
<h3>TODO List</h3>
<!-- To submit task -->
<form id="sub">
<input type="text" autocomplete="off" id = "box">
<button>Submit</button>
</form>
<!-- To display task-->
<ul id="List"></ul>
JS:
// Get references from form, input and ul tags
var inpBox = document.getElementById('box');
var Submit = document.getElementById('sub');
var List = document.getElementById('List');
//function to delete a task
del = (x) =>{
x.parentElement.remove()
}
//Eventlistener to add a task after submition
Submit.addEventListener('submit',(event)=>{
event.preventDefault()
var Temp = `<li>${inpBox.value} <button onclick="del(this)"> Delete </button> </li>`
List.insertAdjacentHTML( "afterEnd",Temp)
})
See here, after submitting a task, it is added to the list but current value is not clear
So we have to clear automatically the input field after the user submits a task. Let’s see how to do that :
2 Ways to Clear input field
1. Clear and Focus() method
To clear the input field you need to assign an empty string to the reference variable of the “
<input>
” element with the “.value()
” method, ex: inpBox.value = ''
. To bring the cursor back to the input field, we need to call the focus()
method of input element, ex : inpBox.focus()
. Remember we have to do all these at the end of submit addEventListener
().//Eventlistener to add a task after submition
Submit.addEventListener('submit',(event)=>{
event.preventDefault()
var Temp = `<li>${inpBox.value} <button onclick="del(this)"> Delete </button> </li>`
List.insertAdjacentHTML( "afterEnd",Temp)
inpBox.value = '' //Clear current input field after submit
inpBox.focus() //To focus the cursor
})
2 reset() method
You can clear the input field and bring the cursor back to the input field in single line by invoking the
reset()
method for the form reference variable.Submit.addEventListener('submit',(event)=>{
event.preventDefault()
var Temp = `<li>${inpBox.value} <button onclick="del(this)"> Delete </button> </li>`
List.insertAdjacentHTML( "afterEnd",Temp)
Submit.reset() // Clear value and focus the cursor the input field
})
live preview:
Conclusion
So, you can use these two methods to clear the input field after submit.