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>
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.
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.
Check out this jsfiddle.
// note the change... I set the disabled property right away <input type="submit" id="register" value="Register" disabled="disabled" />
(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.
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