Using jQuery to enable/disable a button based on a text box

Since this is an html file, just create a blank file on your desktop called Test.html and copy and past the code below.

The steps for doing this are comments in the code.

Note: This should handle typing, pasting, code change, etc…

<!-- Step 1a - Create HTML File (see step 1b way below) -->
<!DOCTYPE html>
    <!-- Step 2 - Include jquery -->
    <script type="text/javascript" src=""></script>
    <!-- Step 3 - Add script to run when page loads -->
    <script  type="text/javascript">
        jQuery(document).ready(function () { 
            <!-- Step 4 - Bind method to text box -->    
            $("#txtField").bind("propertychange keyup input paste", setButtonState);
            <!-- Step 4 - Set the default state -->
		var setButtonState = function () {
			if ($("#txtField").val() == "")
<!-- Step 1b - Add HTML elements --> 
<input type="text" id="txtField" size="50"/>
<button type="button" id="btnEnter">Enter</button>

Update: 5/22/2013: Fixed example. Before if it was used on a page with links, going forward and back could result in the button being disabled even if the text box was populated. This new example solves this issue.

See a MVVM version of this here:
Using MVVM with HTML5 and JavaScript


  1. Nhac DJ says:

    I like the way you conduct your posts. Have a nice Thursday!

  2. [...] Previously I wrote this post: Using jQuery to enable/disable a button based a text box [...]

Leave a Reply

How to post code in comments?