I want my form submit button to be disabled/enabled depending on if the form is completely filled.
When the inputs are filled, the disabled button changes to enabled. That works great. But I would like it to disable the button when an input gets emtied.
This is my script:
<script type="text/javascript" language="javascript"> function checkform() { var f = document.forms["theform"].elements; var cansubmit = true; for (var i = 0; i < f.length; i++) { if (f[i].value.length == 0) cansubmit = false; } if (cansubmit) { document.getElementById('submitbutton').disabled = false; } } </script> <form name="theform"> <input type="text" onKeyup="checkform()" /> <input type="text" onKeyup="checkform()" /> <input id="submitbutton" type="submit" disabled="disabled" value="Submit" /> </form>
Just click f12 in your browser, find the submit button in the html, and then remove the disabled ! It will submit the form even if the inputs are empty.
There is not an option to remove the Submit Button; however, you can choose to hide it on the Form if you'd like, making the "Form" an informational web page/landing page rather than a page that requires/expects action. To do this, you will need to add some CSS code to a Custom Theme.
To disable a button when an input is empty with React, we can set the input's value as a state's value. Then we can use the state to conditionally disable the button when the state's value is empty. to create the name state with the useState hook.
Just use
document.getElementById('submitbutton').disabled = !cansubmit;
instead of the the if-clause that works only one-way.
Also, for the users who have JS disabled, I'd suggest to set the initial disabled
by JS only. To do so, just move the script behind the <form>
and call checkform();
once.
Just add an else
then:
function checkform() { var f = document.forms["theform"].elements; var cansubmit = true; for (var i = 0; i < f.length; i++) { if (f[i].value.length == 0) cansubmit = false; } if (cansubmit) { document.getElementById('submitbutton').disabled = false; } else { document.getElementById('submitbutton').disabled = 'disabled'; } }
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