Enabling a submit button when a textbox has value in jQuery
A common pattern on the web is to only enable a submit button on a form if a value is filled out in a textbox. The other day I was asked by a colleague how to do this in jQuery, and while I gave the basic pseudo code, I was curious on the exact method, so I put this together real quick and decided to share it with the world.
The premise is simple: We want to check the textbox after every time a change is made to it to see if there is any value in it. If there is, we enable the button (by removing the disabled attribute), and if there isn’t, then we make sure the button stays disabled. We initially load the form with the submit button disabled.
The trick to accomplishing this was in coming up with the right event to fire off the textbox. At first I thought the change event would work, but that only fires when the textbox loses focus (not what we want here). Then I tried keypress, but it seems that event gets fired before the textbox is updated, which gives us the previous value, not the current one we need. Finally, I tried the keyup event, and that seems to work just fine.
Below is the code to accomplish this. It might not be the best way to do this, but it works in this case. Also make sure you always validate on the server side as well.
1: <!DOCTYPE html>
2: <html>
3: <head>
4: <title></title>
5: </head>
6:
7: <script src="Scripts/jquery-1.4.4.min.js" type="text/javascript"></script>
8:
9: <script type="text/javascript">
10: $(document).ready(function () {
11: $("#name").keyup(function (data) {
12: if ($(this).val() != "") {
13: $("#enter").removeAttr("disabled");
14: }
15: else {
16: $("#enter").attr("disabled", "disabled");
17: }
18: });
19: });
20: </script>
21:
22: <body>
23: <div>
24: <label for="name">
25: Name</label>
26: <input type="text" id="name" name="name" />
27: <br /><br />
28: <input type="submit" disabled="disabled" value="Enter" id="enter" />
29: </div>
30: </body>
31: </html>