Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disabling submit button until all fields have values

Tags:

jquery

I want to disable my submit button until all the fields have values.. how can I do that?

<html>     <head>         <title></title>         <style type="text/css">         </style>         <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>         <script type="text/javascript">         $(document).ready(function() {             $('#register').attr("disabled", true);         });         </script>     </head>     <body>         <form>         Username<br />         <input type="text" id="user_input" name="username" /><br />         Password<br />         <input type="text" id="pass_input" name="password" /><br />         Confirm Password<br />         <input type="text" id="v_pass_input" name="v_password" /><br />         Email<br />         <input type="text" id="email" name="email" /><br />              <input type="submit" id="register" value="Register" />         </form>         <div id="test">         </div>     </body> </html> 
like image 796
AndrewFerrara Avatar asked Apr 10 '11 20:04

AndrewFerrara


People also ask

How do you disable button until all fields are entered 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.

How do I make my submit button disabled?

1.1 To disable a submit button, you just need to add a disabled attribute to the submit button. $("#btnSubmit"). attr("disabled", true); 1.2 To enable a disabled button, set the disabled attribute to false, or remove the disabled attribute.


1 Answers

Check out this jsfiddle.

HTML

// note the change... I set the disabled property right away <input type="submit" id="register" value="Register" disabled="disabled" /> 

JavaScript

(function() {     $('form > input').keyup(function() {          var empty = false;         $('form > input').each(function() {             if ($(this).val() == '') {                 empty = true;             }         });          if (empty) {             $('#register').attr('disabled', 'disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie         } else {             $('#register').removeAttr('disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie         }     }); })() 

The nice thing about this is that it doesn't matter how many input fields you have in your form, it will always keep the button disabled if there is at least 1 that is empty. It also checks emptiness on the .keyup() which I think makes it more convenient for usability.

like image 173
Hristo Avatar answered Oct 24 '22 17:10

Hristo