Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable/Enable Submit Button until all forms have been filled

Tags:

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> 
like image 573
user1912654 Avatar asked Dec 18 '12 11:12

user1912654


People also ask

How do you disable submit button until all fields are filled?

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.

How do I turn off the submit button in Microsoft forms?

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.

How do you disable submit button until form is filled in React?

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.


2 Answers

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.

like image 153
Bergi Avatar answered Sep 29 '22 09:09

Bergi


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';     } } 
like image 37
Mario S Avatar answered Sep 29 '22 10:09

Mario S