Sometimes, we want to disable or enable submit button until all forms have been filled with JavaScript.
In this article, we’ll look at how to disable or enable submit button until all forms have been filled with JavaScript.
How to disable or enable submit button until all forms have been filled with JavaScript?
To disable or enable submit button until all forms have been filled with JavaScript, we can set the disabled
property according to the input values.
For instance, we write:
<form name="theForm">
<input type="text" />
<input type="text" />
<input id="submitbutton" type="submit" disabled />
</form>
We have a form that has 2 text inputs and a submit button.
Then to enable the submit button only when all the text inputs are filled, we write:
document.onkeyup = (e) => {
if (e.target.tagName === 'INPUT') {
const canSubmit = [...document.forms.theForm.querySelectorAll('input[type="text"]')]
.every(i => {
return i.value
})
document.forms.theForm.querySelector('input[type="submit"]').disabled = !canSubmit
}
}
We set the document.onkeyup
function to a function that checks if the keyup event is triggered by an input element.
If it is, then we check if all the text inputs are filled with:
const canSubmit = [...document.forms.theForm.querySelectorAll('input[type="text"]')]
.every(i => {
return i.value
})
Then we set the disabled
attribute of the submit button with:
document.forms.theForm.querySelector('input[type="submit"]').disabled = !canSubmit
Now the submit button is only enabled when all the text inputs are filled.
Conclusion
To disable or enable submit button until all forms have been filled with JavaScript, we can set the disabled
property according to the input values.