Quick Tip – Disable/Enable Button by Textbox Client Event using jQuery

September 16, 2010

no comments

Quick Tip – Disable/Enable Button by Textbox Client Event using jQuery


I find myself often with a need to disable/enable a button according to client events that occur on web pages. jQuery LogoToday I helped to implement this behavior again so I thought it will be nice to share the code I used. In this example I’m disabling/enabling a button according to whether a textbox holds some text. I’m using jQuery to make the code simple. Pay attention that this solution can be implemented for other events also.


The Code



$(document).ready(function () {
    $(‘#txtAgentName’).blur(function () {
        if ($.trim(this.value) == “”) {
            $(‘#btnUpdate’).attr(“disabled”, true);
        }
        else {
            $(‘#btnUpdate’).removeAttr(“disabled”);
        }
    });
});  

As you can see I wire up the ready event of the page and hook a blur event to the textbox with the txtAgentName id. In the blur event I check the value of the textbox and if it is empty I disable the button and if it is not I enable the button. The page that this example is taken from is an MVC 2 view which holds the textbox and the button elements like the following elements:



<input id=“btnUpdate” type=“submit” value=“Update” disabled />
<%= Html.TextBox(“txtAgentName”) %>

Summary


A lot was written about how jQuery simplify the Javascript code that you write. In this tip I used jQuery to set Html elements appearance when some client event occurs.  


Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*